How to create and manipulate arrays and objects using JavaScript's map, filter, and reduce functions?

JavaScript's map, filter, and reduce functions are powerful tools for creating and manipulating arrays and objects. They allow you to iterate over arrays and objects and perform certain operations on their elements. Here's how you can use these functions:

  1. create an array:
const myArray = [1, 2, 3, 4, 5];
  1. create an object:
const myObject = { name: 'John', age: 30, gender: 'male' };

Using Map:

The map function allows you to transform each element of an array and create a new array with the transformed elements.

const newArray = myArray.map((element) => { // perform transformation on each element here return element * 2; }); console.log(newArray); // Output: [2, 4, 6, 8, 10]

Using Filter:

The filter function allows you to create a new array that contains only the elements that satisfy a certain condition.

const filteredArray = myArray.filter((element) => { // specify the condition to filter by return element > 3; }); console.log(filteredArray); // Output: [4, 5]

Using Reduce:

The reduce function allows you to perform a calculation on the elements of an array and accumulate the result.

const totalSum = myArray.reduce((accumulator, element) => { // perform accumulation on each element return accumulator + element; }, 0); // the initial value of the accumulator console.log(totalSum); // Output: 15

To use these functions on objects, you can convert the object into an array using Object.entries or Object.keys method and then apply the desired function.

For example, to convert an object into an array using Object.entries:

const myObjectArray = Object.entries(myObject); console.log(myObjectArray); // Output: [['name', 'John'], ['age', 30], ['gender', 'male']]

Now, you can apply the map, filter, and reduce functions to myObjectArray to transform, filter, and accumulate the elements as required.

Remember that these functions do not modify the original array or object, but instead return a new array or object with the desired changes.