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.

Categories
JavaScript Answers

How to find first element of array matching a boolean condition in JavaScript?

To find first element of array matching a boolean condition in JavaScript, we use the find method.

For instance, we write

const result = someArray.find(isNotNullNorUndefined);

to call someArray.find with the isNotNullNorUndefined function which returns the boolean condition we’re looking for.

The first item with the condition if it’s found.