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.

Categories
JavaScript Answers

How to change value of object which is inside an array using JavaScript?

To change value of object which is inside an array using JavaScript, we use findIndex to find the item.

For instance, we write

const myArray = [
  { id: 0, name: "John" },
  { id: 1, name: "Sara" },
  { id: 2, name: "Domnic" },
  { id: 3, name: "Bravo" },
];

const objIndex = myArray.findIndex((obj) => obj.id == 1);
myArray[objIndex].name = "Bob";

to call findIndex to find index of the object in myArray with id 1.

Then we use the index to get the item from myArray and assign its name property to 'Bob'.