Categories
JavaScript Answers

How to add values to an array of objects dynamically in JavaScript?

To add values to an array of objects dynamically in JavaScript, we use the spread syntax.

For instance, we write

let data = [
  { label: "1", value: 12 },
  { label: "1", value: 12 },
  { label: "1", value: 12 },
];

data = [...data, { label: "2", value: 14 }];

to spread the entries in data with ... into a new array.

And then we add another object at the end of the new array.

We then assign the new array as the value of data.

Categories
JavaScript Answers

How to use array reduce with condition in JavaScript?

To use array reduce with condition in JavaScript, we call filter to return a filtered array.

For instance, we write

const sum = records
  .filter(({ gender }) => gender === "male")
  .reduce((sum, record) => sum + record.value);

to call recorda.filter to return an array where the gender property in the object in the array is 'male'.

Then we call reduce with a callback to return the sum of the partial sum sum and record.value.

Categories
JavaScript Answers

How to filter an array or object by checking multiple values with JavaScript?

To filter an array or object by checking multiple values with JavaScript, we use the filter method.

For instance, we write

const find = myArray.filter((result) => {
  return result.param1 === "string1" && result.param2 === "string2";
});

to call myArray.filter with a function that checks if the result object in myArray that’s being looped through has the params1 property equal to 'string1' and params2 equals to 'string2'.

An array with the objects that meets the condition is returned.

Categories
JavaScript Answers

How to store JavaScript functions in arrays?

To store JavaScript functions in arrays, we reference the function in an array.

For instance, we write

const yourFunction = () => {
  console.log("I am your function");
};

const group = [0, "abc", false, yourFunction];

group[3]();

to put yourFunction in the group array.

Then we call yourFunction with group[3]().

Categories
JavaScript Answers

How to get the previous and next elements of an array loop in JavaScript?

To get the previous and next elements of an array loop in JavaScript, we use the modulo operator.

For instance, we write

const len = array.length;

const current = array[i];
const previous = array[(i + len - 1) % len];
const next = array[(i + 1) % len];

to get the current array item with index i.

We get the previous item’s index with (i + len - 1) % len.

And we get the next item with index (i + 1) % len.