Categories
JavaScript Answers

How to use the reduce function to return a JavaScript array?

To use the reduce function to return a JavaScript array, we return the array in the reduce callback.

For instance, we write

const store = [0, 1, 2, 3, 4];

const stored = store.reduce((pV, cV, cI) => {
  return [...pV, cV];
}, []);

console.log(stored);

to call store.reduce with a callback that destructures the pV array we get from the reduce process.

And then we spread the entries from there and the put cV at the end of it and return the array.

Categories
JavaScript Answers

How to loop through array backwards with forEach with JavaScript?

To loop through array backwards with forEach with JavaScript, we call reverse before calling forEach.

For instance, we write

const arr = [1, 2, 3];

arr
  .slice()
  .reverse()
  .forEach((x) => console.log(x));

to call arr.slice to return a copied version of the arr array.

And then we call reverse to reverse the copied array.

Then we call forEach with a callback to log each entry x being looped through.

Categories
JavaScript Answers

How to print JSON data in JavaScript console.log?

To print JSON data in JavaScript console.log, we use the '%j' option.

For instance, we write

console.log("%j", jsonObj);

to call console.log with "%j" and the jsonObj object to print JSON objects with console.log.

Categories
JavaScript Answers

How to compare two arrays of objects, and exclude the elements who match values into new array in JavaScript?

To compare two arrays of objects,and exclude the elements who match values into new array in JavaScript, we use the filter and some methods.

For instance, we write

const result = result1.filter((o1) => !result2.some((o2) => o1.id === o2.id));

to call result1.filter with a callback that checks if result2 don’t have items that have o2 in result1‘s id that’s equal to o2 in result2‘s id.

Then an array with the objects in result1 where id property isn’t equal to objects in result2‘s id property are included.

Categories
JavaScript Answers

How to push object into array with JavaScript?

To push object into array with JavaScript, we use the push method.

For instance, we write

const nietos = [];
nietos.push({ "01": nieto.label, "02": nieto.value });

to call nietos.push with an object to append it has the last item of the nietos array.