HomeToolsAbout

filter

What is it

The filter() method does not change the original array

  • deep copy
const oldArray = [ { "name": "Raj", "age":"15", "RollNumber": "123", "Marks": "99", }, { "name": "Aman", "age":"14", "RollNumber": "223", "Marks": "69", }, ]; const newArray = oldArray.filter(el => el.age >= 15); console.log(newArray); // [{ name: 'Raj', Age: '15', RollNumber: '123', Marks: '99' }] console.log(oldArray); // same as before applying filter

Chaining multiple filter conditions at once

const filteredResult = arrData.filter( x => x.price <= 1000 && x.sqft >= 500 && x.num_of_beds >=2 && x.num_of_baths >= 2.5 );

Using predefined Boolean expression in filter

Predefining the callback functions to a boolean-resulting variable, filtering chain becomes more legible

// original array const input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // boolean output function const isEven = (value) => value % 2 === 0; const isOdd = (value) => !isEven(value); const isPrime = (value) => { for (let i = 2, s = Math.sqrt(value); i <= s; i++) { if (value % i === 0) return false; } return value > 1; }; // filters using expression const even = input.filter(isEven); const odd = input.filter(isOdd); const prime = input.filter(isPrime); console.log({ input, even, odd, prime }); /* input: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], even: [2, 4, 6, 8, 10], odd: [1, 3, 5, 7, 9], prime: [2, 3, 5, 7], */
AboutContact