How to Filter an Array in JavaScript

How to filter an array from all elements of another array

You can use the this parameter of the filter() function to avoid to store your filter array in a global variable.

var filtered = [1, 2, 3, 4].filter(    function(e) {      return this.indexOf(e) < 0;    },    [2, 4]);console.log(filtered);

How to filter an array in array of objects in Javascript?

filter() -> uses a callback function the return value of which decides what will be returned in the filtered array. If return value is true, the item is included in the resultant array.

includes() -> searches for something in an array of items using == equality

const books = [{
id: "1",
title: "Book title",
areas: ["horror", "mystery"]
}, {
id: "2",
title: "Book title 2",
areas: ["friendship", "love", "history"]
},
{
id: "3",
title: "Book title 3",
areas: ["friendship", "scifi"]
}
];

const filterValue = "horror";
const filteredBooks = books.filter(val => val.areas.includes(filterValue));
console.log(filteredBooks);

How to filter an array in javascript?

You should use filter method, which accepts a callback function.

The filter() method creates a new array with all elements that pass
the test implemented by the provided function.

Also, use typeof operator in order to find out the type of item from array. The typeof operator returns a string indicating the type of the unevaluated operand.

let total = ["10%", "1000", "5%", "2000"];let percentage = total.filter(function(item){  return typeof item == 'string' && item.includes('%');});console.log(percentage);let absolute = total.filter(function(item){  return typeof item == 'number' || !isNaN(item);});console.log(absolute);

How to filter object array based on attributes?

You can use the Array.prototype.filter method:

var newArray = homes.filter(function (el) {
return el.price <= 1000 &&
el.sqft >= 500 &&
el.num_of_beds >=2 &&
el.num_of_baths >= 2.5;
});

Live Example:

var obj = {    'homes': [{            "home_id": "1",            "price": "925",            "sqft": "1100",            "num_of_beds": "2",            "num_of_baths": "2.0",        }, {            "home_id": "2",            "price": "1425",            "sqft": "1900",            "num_of_beds": "4",            "num_of_baths": "2.5",        },        // ... (more homes) ...         ]};// (Note that because `price` and such are given as strings in your object,// the below relies on the fact that <= and >= with a string and number// will coerce the string to a number before comparing.)var newArray = obj.homes.filter(function (el) {  return el.price <= 1000 &&         el.sqft >= 500 &&         el.num_of_beds >= 2 &&         el.num_of_baths >= 1.5; // Changed this so a home would match});console.log(newArray);

Filter an array of objects according to the name of the key in the objects

Use the in operator to check if a property exists on the object:

const dataArray = [{"name":"David"},{"location":"New York"},{"name":"Jenna"}];

// name exists on the object
console.log(dataArray.filter(item => 'name' in item));

// or location doesn't exist on the object
console.log(dataArray.filter(item => !('location' in item)));

Filter an Array of strings using Filtered String and Remove from Original Array

Since you want to mutate the original array then you can do as:

let guests = [
"Partner",
"Evil Nice Relative 1",
"Nice Relative 2",
"Evil One",
"another evil",
"another one",
"another evil is here",
"strange Evil is here",
"someone Nicer",
"Ugly Evil Bad",
];

const filterString = "Evil";

function checkEvil() {
for (let i = guests.length - 1; i >= 0; i--) {
const element = guests[i];
if (element.toLowerCase().indexOf(filterString.toLowerCase()) !== -1) {
guests.splice(i, 1);
}
}
console.log(guests);
}

checkEvil();

Filter an array of objects by another object of filters

You can achieve this result using filter, Object.keys, and every.

You have to use filter and pass predicate that tell whether it is included in the final result.

In predicate, loop over all properties on the filters object and match if it is present in data or not. Simple

data.filter((o) =>Object.keys(filters).every((k) => filters[k] === o[k]));

const data = [{
level: "1",
objectId: "11",
objectIdNo: "320",
wpId: "123",
},
{
level: "2",
objectId: "12",
objectIdNo: "321",
wpId: "123",
},
{
level: "2",
objectId: "13",
objectIdNo: "322",
wpId: "120",
},
];

const filters = {
level: "2",
wpId: "123",
};

const result = data.filter((o) =>
Object.keys(filters).every((k) => filters[k] === o[k])
);
console.log(result);


Related Topics



Leave a reply



Submit