Categories
JavaScript Answers

How to filter and delete filtered elements in an array with JavaScript?

To filter and delete filtered elements in an array with JavaScript, we use the splice and findIndex methods.

For instance, we write

const a = [{ name: "tc_001" }, { name: "tc_002" }, { name: "tc_003" }];
a.splice(
  a.findIndex((e) => e.name === "tc_001"),
  1
);

to call a.findIndex with a callback that checks if name is 'tc_001' in the object being looped through to get the index with name property equal to ‘tc_001’ina`.

Then we call splice with the index and 1 to remove the item in a with such condition.

Categories
JavaScript Answers

How to create array from for loop with JavaScript?

To create array from for loop with JavaScript, we use the fill and map methods.

For instance, we write

const yearStart = 2000;
const yearEnd = 2040;
const years = Array(yearEnd - yearStart + 1)
  .fill()
  .map((_, i) => yearStart + i);

to create an array with length yearEnd - yearStart + 1 with Array.

Then we call fill to fill the empty slots with undefined.

And then we call map with a callback to map the undefined values to yearStart + i where i is the index of the array currently being looped through.

Categories
JavaScript Answers

How to create a single value array in JavaScript?

To create a single value array in JavaScript, we use the array literal syntax.

For instance, we write

const arr = [21];

to define the arr array with value 21 inside.

Categories
JavaScript Answers

How to prevent adding duplicate keys to a JavaScript array?

To prevent adding duplicate keys to a JavaScript array, we use sets.

For instance, we write

const set = new Set();
set.add(1);
set.add(2);
set.add(3);

console.log(set);

to create a new set with the Set constructor.

Then we call add to add the entries into the set.

Duplicate entries won’t be added to the set with add.

Categories
JavaScript Answers

How to replace elements in array with elements of another array with JavaScript?

To replace elements in array with elements of another array with JavaScript, we use the splice method.

For instance, we write

const a = [1, 2, 3, 4, 5];
const b = [10, 20, 30];
a.splice(0, b.length, ...b);

to call a.splice with 0, b.length and the elements in b as arguments to replace the items in a between index 0 and b.length - 1 with the items in b in place.