Categories
JavaScript Answers

How to remove first element from array and return the array minus the first element with JavaScript?

To remove first element from array and return the array minus the first element with JavaScript, we call the shift method.

For instance, we write

const myArray = ["item 1", "item 2", "item 3", "item 4"];

myArray.shift();
console.log(myArray);

to call myArray.shift to remove the first item of myArray in place.

Categories
JavaScript Answers

How to find the index of an object whose attributes match a search within an array of JavaScript objects?

To find the index of an object whose attributes match a search within an array of JavaScript objects, we use the findIndex method.

For instance, we write

const item = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }].findIndex(
  (obj) => obj.id == 3
);

to call findIndex on the [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }] array to find the index of the item with the id property equal to 3.

Categories
JavaScript Answers

How to use map() on an array in reverse order with JavaScript?

To use map() on an array in reverse order with JavaScript, we make a copy before we reverse the array.

For instance, we write

myArray
  .slice(0)
  .reverse()
  .map((a) => {
    //...
  });

to call slice to make a copy of myArray and return it.

And then we call reverse to reverse the copied array.

Then we call map to map the entries of the reversed array.

Categories
JavaScript Answers

How to unpack array into separate variables in JavaScript?

To unpack array into separate variables in JavaScript, we use destructuring.

For instance, we write

const arr = ["one", "two"];
const [one, two] = arr;

to assign the entries in arr into their own variables with the destructuring syntax.

So one is 'one' and two is 'two'.

Categories
JavaScript Answers

How to check if two arrays have the same values with JavaScript?

To check if two arrays have the same values with JavaScript, we sort them before comparing them.

For instance, we write

const array1 = [
  10, 6, 19, 16, 14, 15, 2, 9, 5, 3, 4, 13, 8, 7, 1, 12, 18, 11, 20, 17,
];
const array2 = [
  12, 18, 20, 11, 19, 14, 6, 7, 8, 16, 9, 3, 1, 13, 5, 4, 15, 10, 2, 17,
];

if (array1.sort().join(",") === array2.sort().join(",")) {
  console.log("same members");
}

to call sort to sort the numbers in the arrays and then we call join to join the entries with commas to form a string.

Then we compare them with === to see if they’re the same.