Categories
JavaScript Answers

How to compute a set difference using JavaScript arrays?

To compute a set difference using JavaScript arrays, we use the filter method.

For instance, we write

const a = [1, 2, 3, 4];
const b = [1, 3, 4, 7];

const diff = a.filter((x) => {
  return b.indexOf(x) < 0;
});

console.log(diff);

to call a.filter with a callback that checks if the item x in a isn’t in b with b.indexOf(x) < 0.

An array with the items in a but not in b is then returned.

Categories
JavaScript Answers

How to find index of all occurrences of element in array?

To find index of all occurrences of element in array, we use the map and filter method.

For instance, we write

const nanoIndexes = cars
  .map((car, i) => (car === "Nano" ? i : -1))
  .filter((index) => index !== -1);

to call map with a callback that checks if the car value being iterated through is 'Nano'.

If it is, we return i and we return -1 otherwise.

Then we call filter with a callback that returns an array with the index value not equal to -1.

Categories
JavaScript Answers

How to create object from array with JavaScript?

To create object from array with JavaScript, we can use the Object.fromEntries method.

For instance, we write

const dynamicArray = ["2007", "2008", "2009", "2010"];
const obj = Object.fromEntries(
  dynamicArray.map((year) => [
    year,
    {
      something: "based",
      on: year,
    },
  ])
);

console.log(obj);

to call Object.fromEntries with an array that we get from the map method called with a callback that returns arrays with the key and value of each property.

We use Object.fromEntries to convert the nested key-value pair array to an object.

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.