Categories
JavaScript Answers

How to truncate an array with JavaScript?

To truncate an array with JavaScript, we use the slice method.

For instance, we write

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr = arr.slice(0, 4);
console.log(arr);

to call arr.slice with 0 and 4 to return an array with the arr array items between index 0 and 3.

And we assign the returned array back to arr to update it.

Categories
JavaScript Answers

How to convert a JavaScript iterable to an array?

To convert a JavaScript iterable to an array, we use the spread operator.

For instance, we write

const x = new Set([1, 2, 3, 4]);
const z = [...x];

to create a set with the Set constructor.

Then we convert the set to an array with the spread operator.

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.