Categories
JavaScript Answers

How to find object by id in an array of JavaScript objects?

To find object by id in an array of JavaScript objects, we use the find method.

For instance, we write

const myArray = [
  { id: "73", foo: "bar" },
  { id: "45", foo: "bar" },
  //...
];
const foo = myArray.find((x) => x.id === "45").foo;

to call myArray.find with a callback that checks if the id property of the item is '45'.

If it’s true, then the object is returned.

And then we get the foo property of it.

Categories
JavaScript Answers

How to check if a variable is an array in JavaScript?

To check if a variable is an array in JavaScript, we use the Array.isArray method.

For instance, we write

const isArray = Array.isArray(value);

to call Array.isArray with value to check if value is an array.

If it is, then true is returned.

Categories
JavaScript Answers

How to copy array by value with JavaScript?

To copy array by value with JavaScript, we use the slice method.

For instance, we write

const oldArray = [1, 2, 3, 4, 5];
const newArray = oldArray.slice();

to call oldArray.slice with no arguments to make a copy of oldArray and return it.

Categories
JavaScript Answers

How to short circuit Array.forEach like calling break with JavaScript?

To short circuit Array.forEach like calling break with JavaScript, we use a for-of loop.

For instance, we write

const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (const el of arr) {
  console.log(el);
  if (el === 5) {
    break;
  }
}

to use a for-of loop to loop through the arr array.

And we use break to stop the loop when el is 5.

el is the element we’re looping through.

Categories
JavaScript Answers

How to add new array elements at the beginning of an array in JavaScript?

To add new array elements at the beginning of an array in JavaScript, we use the unshift method.

For instance, we write

const a = [23, 45, 12, 67];
a.unshift(11);
console.log(a);

to call a.unshift with 11 to prepend 11 to the a array.