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.
Also, useThe filter() method creates a new array with all elements that pass
the test implemented by the provided function.
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
Why Are Es6 Classes Not Hoisted
Splicing a JavaScript Array from Within the Callback Passed to Foreach
Get Selected Value/Text from Select on Change
React Doesn't Reload Component Data on Route Param Change or Query Change
Why Do Empty JavaScript Arrays Evaluate to True in Conditional Structures
How to Write Regex to Validate Dates
Different Result for Yyyy-Mm-Dd and Yyyy/Mm/Dd in JavaScript When Passed to "New Date"
Create File with Google Drive API V3 (Javascript)
Pass Post Data with Window.Location.Href
How to Access Object Using Dynamic Key
Find the Exact Height and Width of the Viewport in a Cross-Browser Way (No Prototype/Jquery)
Google Maps API Autocomplete 2Nd Address Fields on Same Page
Window.Location.Reload with Clear Cache
JavaScript Object Literals Syntax Error
Angularjs Routing 404 Error with HTML5 Mode
How Is a JavaScript Hash Map Implemented
Rotate Object on Specific Axis Anywhere in Three.Js - Including Outside of Mesh