Array filter exaample new array
Here is an example of using the filter()
method to create a new array from an existing array:
const originalArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const newArray = originalArray.filter((element) => element % 2 === 0);
console.log(newArray); // Output: [2, 4, 6, 8, 10]
In this example, the filter()
method is used to create a new array (newArray
) from the originalArray
. The callback function (element) => element % 2 === 0
is used to filter the elements of the original array. This callback function returns true
for elements that are even (i.e., element % 2 === 0
) and false
for elements that are odd.
The resulting newArray
contains only the even numbers from the original array.
Here are some more examples:
const originalArray = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
const newArray = originalArray.filter((fruit) => fruit.startsWith('a'));
console.log(newArray); // Output: ['apple', 'elderberry']
const originalArray = [{ name: 'John', age: 25 }, { name: 'Jane', age: 30 }, { name: 'Bob', age: 35 }];
const newArray = originalArray.filter((person) => person.age > 30);
console.log(newArray); // Output: [{ name: 'Jane', age: 30 }, { name: 'Bob', age: 35 }]
In these examples, the filter()
method is used to create new arrays by filtering the elements of the original arrays based on specific conditions.