Categories
JavaScript Answers

How to merge two arrays in JavaScript and de-duplicate items?

To merge two arrays in JavaScript and de-duplicate items, we use the spread operator.

For instance, we write

const array1 = ["foo", "bar"];
const array2 = ["baz", "qux"];
console.log(Array.from(new Set([...array1, ...array2])));

to put all the items in array1 and array2 into a new array with the spread operator.

Then we create a new set from the array with the Set constructor to remove the duplicates.

And then we call Array.from with the set to convert it back to an array.

Categories
JavaScript Answers

How to create an array containing 1…N with JavaScript?

To create an array containing 1…N with JavaScript, we use the array keys method.

For instance, we write

const a = Array.from(Array(10).keys());

to call Array(10).keys() to get an array of indexes of the array with length 10.

Then we use Array.from to create a copy of the array and return it.

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.