Categories
JavaScript Answers

How to get the index of an object by its property in JavaScript?

To get the index of an object by its property in JavaScript, we use the map and indexOf methods.

For instance, we write

const data = [
  { id: 1, name: "Nick", token: "312312" },
  { id: 2, name: "John", token: "123123" },
];
const index = data.map((e) => e.name).indexOf("Nick");

to call data.map with a callback to return an array with the name property of each object.

And then we call indexOf to get the index of the entry with 'Nick' in the returned array.

Categories
JavaScript Answers

How to concatenate N arrays with JavaScript?

To concatenate N arrays with JavaScript, we use the spread operator and push.

For instance, we write

const a = [1, 2],
  b = ["x", "y"],
  c = [true, false];
a.push(...b, ...c);

to call a.push with the entries from b and c spread as arguments to put the entries into a.

Categories
JavaScript Answers

How to get subarray from array with JavaScript?

To get subarray from array with JavaScript, we use the slice method.

For instance, we write

const ar = [1, 2, 3, 4, 5];
const ar2 = ar.slice(1, 4);

console.log(ar2);

to call ar.slice with 1 and 4 to return a new array with the entries in ar from index 1 to 3.

Categories
JavaScript Answers

How to group an array of objects by key with JavaScript?

To group an array of objects by key with JavaScript, we use the Lodash groupBy method.

For instance, we write

const cars = [
  {
    make: "audi",
    model: "r8",
    year: "2012",
  },
  {
    make: "audi",
    model: "rs5",
    year: "2013",
  },
  {
    make: "ford",
    model: "mustang",
    year: "2012",
  },
  {
    make: "ford",
    model: "fusion",
    year: "2015",
  },
  {
    make: "kia",
    model: "optima",
    year: "2012",
  },
];

const grouped = _.groupBy(cars, (car) => car.make);

console.log(grouped);

to call groupBy with the cars array and a function that returns the value of the make property in each entry to return an array that’s grouped by the make property.

Categories
JavaScript Answers

How to pass an array as a function parameter in JavaScript?

To pass an array as a function parameter in JavaScript, we use the spread operator.

For instance, we write

const x = ["p0", "p1", "p2"];
func(...x);

to call func with the entries of x as arguments with the spread operator.