Categories
JavaScript Answers

How to set all values of an array with JavaScript?

To set all values of an array with JavaScript, we use the fill method.

For instance, we write

const arr = new Array(3).fill(9);

to create an empty array with length 3 with Array(3).

Then we call fill with 9 to fill the empty slots with 9’s.

Categories
JavaScript Answers

How to slice an object in JavaScript?

To slice an object in JavaScript, we use the Object.entries and Object.fromEntries methods.

For instance, we write

const obj = {
  0: "zero",
  1: "one",
  2: "two",
  3: "three",
  4: "four",
};
const res = Object.fromEntries(Object.entries(obj).slice(0, 4));

to call Object.entries with obj to return an array of key-value pair arrays in obj.

Then we call slice to return a slice of the key-value pair array we want.

And then we call Object.fromEntries with the sliced array to convert it back to an object.

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.