Categories
JavaScript Answers

How to convert JavaScript NodeList to an array?

To convert JavaScript NodeList to an array, we use the Array.from method.

For instance, we write

const myArray = Array.from(nl);

to call Array.from with nl to convery the nl node list into an array.

Categories
JavaScript Answers

How to prepend a value to an array with JavaScript?

To prepend a value to an array with JavaScript, we call the unshift method.

For instance, we write

a.slice().unshift(0);

to call a.slice to make copy of the a array.

And then we call unshift on the copied array to prepend 0 into the array.

Categories
JavaScript Answers

How to get the index of an object by its property in JavaScript?

To get the index of an object by its property in JavaScript, we use the map and indexOf methods.

For instance, we write

const data = [
  { id: 1, name: "Nick", token: "312312" },
  { id: 2, name: "John", token: "123123" },
];
const index = data.map((e) => e.name).indexOf("Nick");

to call data.map with a callback to return an array with the name property of each object.

And then we call indexOf to get the index of the entry with 'Nick' in the returned array.

Categories
JavaScript Answers

How to concatenate N arrays with JavaScript?

To concatenate N arrays with JavaScript, we use the spread operator and push.

For instance, we write

const a = [1, 2],
  b = ["x", "y"],
  c = [true, false];
a.push(...b, ...c);

to call a.push with the entries from b and c spread as arguments to put the entries into a.

Categories
JavaScript Answers

How to get subarray from array with JavaScript?

To get subarray from array with JavaScript, we use the slice method.

For instance, we write

const ar = [1, 2, 3, 4, 5];
const ar2 = ar.slice(1, 4);

console.log(ar2);

to call ar.slice with 1 and 4 to return a new array with the entries in ar from index 1 to 3.