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.

Categories
JavaScript Answers

How to sort array of objects by single key with date value with JavaScript?

To sort array of objects by single key with date value with JavaScript, we can subtract the timestamps.

For instance, we write

const arr = [
  {
    updatedAt: "2022-01-01T06:25:24Z",
    foo: "bar",
  },
  {
    updatedAt: "2022-01-09T11:25:13Z",
    foo: "bar",
  },
  {
    updatedAt: "2022-01-05T04:13:24Z",
    foo: "bar",
  },
];
const sorted = arr.sort(
  (a, b) => +new Date(a.updatedAt) - +new Date(b.updatedAt)
);

to call arr.sort with a callback that converts updateAt to dates with the Date constructor.

And then we convert them to timestamps in milliseconds with +.

Finally, we subtract them to compare them.

A new array with the sorted values is returned.

Categories
JavaScript Answers

How to set DOM element as first child with JavaScript?

To set DOM element as first child with JavaScript, we call the prepend method.

For instance, we write

parent.prepend(newChild);

to call prepend with newChild to put newChild before all other child nodes in parent.

Categories
JavaScript Answers

How to call array.push() if item does not exist with JavaScript?

To call array.push() if item does not exist with JavaScript, we use findIndex to check for item before we call push.

For instance, we write

const arrayObj = [
  { name: "bull", text: "red" },
  { name: "tom", text: "tasty" },
  { name: "tom", text: "tasty" },
];
const index = arrayObj.findIndex((x) => x.name == "bob");
if (index === -1) {
  arrayObj.push(obj);
} else {
  console.log("object already exists");
}

to call findIndex to get the index of the first object with name equal to 'Bob'.

If it returns -1, then we call push to append obj as the last item of the arrayObj array.