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);
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: "2",
title: "Book title 3",
areas: ["friendship", "scifi"]
}
];
const filterValue = "horror";
const filteredBooks = books.filter(val => val.areas.includes(filterValue));
console.log(filteredBooks);
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);
How to filter an array of objects by unique ID and unique name?
You can simply use &&
to include additional criteria that needs to be met: in your example, you want both the id
and name
to match:
const filteredData = data.filter((value, index, self) =>
self.findIndex(v => v.id === value.id && v.name === value.name) === index
);
If you have multiple keys you want to consider and you don't want to write multiple &&
statements, you can simply store the keys in an array, and then use Array.prototype.every()
to enforce the match:
const keys = ['id', 'name'];
const filteredData = data.filter((value, index, self) =>
self.findIndex(v => keys.every(k => v[k] === value[k])) === index
);
See proof-of-concept below:
const data = [{
id: 1234,
name: 'Name1'
},
{
id: 5678,
name: 'Name1'
},
{
id: 1234,
name: 'Name1'
},
{
id: 5678,
name: 'Name2'
},
];
const keys = ['id', 'name'];
const filteredData = data.filter((value, index, self) =>
self.findIndex(v => keys.every(k => v[k] === value[k])) === index
);
console.log(filteredData);
Typescript Filter Array of Objects by Duplicate Properties
- Group the values by their
name
using Array.prototype.reduce - Filter the groups where the length is greater than
1
using Array.prototype.filter. - And finally flatten the resultant array using Array.prototype.flat.
const values = [{ id: 1, name: "a" }, { id: 2, name: "b" }, { id: 3, name: "c" }, { id: 4, name: "a" }];
const duplicates = Object.values(
values.reduce((r, v) => ((r[v.name] ??= []).push(v), r), {})
)
.filter((g) => g.length > 1)
.flat();
console.log(duplicates);
How to filter array of object inside the array of the object type in JavaScript?
You can look through each countries
object and add your data in a Set
to get unique country.
const data = [ {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "US"}, {type: "County", countyName: "US"}, {type: "County", countyName: "US"}]}, {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "German"}, {type: "County", countyName: "German"}, {type: "County", countyName: "German"}]}, {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "Japan"}, {type: "County", countyName: "German"}, {type: "County", countyName: "German"}]}, ],
result = Array.from(data.reduce((r, {countries}) => {
countries.forEach(({countyName}) => r.add(countyName));
return r;
}, new Set()));
console.log(result);
Filter/Reduce array of objects into a new object based on day
Gets a unique list of days and builds an object based on the calculated days
const data = [ { unixDate: 1650348034, dateTime: "Tue Apr 19 2022 23:00:34", severityLevel: 1, severity: "Light" }, { unixDate: 1650348034, dateTime: "Tue Apr 19 2022 14:00:34", severityLevel: 3, severity: "Moderate" }, { unixDate: 1650440700, dateTime: "Wed Apr 20 2022 15:45:00", severityLevel: 2, severity: "Moderate-Light" }, { unixDate: 1650442500, dateTime: "Wed Apr 20 2022 15:45:00", severityLevel: 4, severity: "Heavy" }, { unixDate: 1650427234, dateTime: "Wed Apr 20 2022 12:00:00", severityLevel: 3, severity: "Moderate" } ]
//Get unique list of days
let unique = [... new Set(data.map(d => new Date(d.unixDate * 1000).toLocaleDateString("en-US")))];
//build object based on this list
let results = Object.fromEntries(unique.map(m => {
let records = data.filter(v => new Date(v.unixDate * 1000).toLocaleDateString("en-US") === m);
return [records[0].unixDate, records.reduce((v,o) => v+=o.severityLevel, 0) / records.length ]
}));
console.log(results);
Related Topics
How to Display Length of Filtered Ng-Repeat Data
How to Get Element by Xpath Using JavaScript in Selenium Webdriver
How to Use Async/Await at the Top Level
Detecting Arrow Key Presses in JavaScript
Differencebetween Screenx/Y, Clientx/Y and Pagex/Y
Angularjs Ui-Router Login Authentication
Navigator.Geolocation.Getcurrentposition Sometimes Works Sometimes Doesn'T
How to Handle Anchor Hash Linking in Angularjs
Parse Datetime String in JavaScript
Dealing with Float Precision in JavaScript
Constructor Function VS Factory Functions
Multiple Assignment in JavaScript? What Does [A,B,C] = [1, 2, 3]; Mean
How to Bind Fancybox to Dynamic Added Element
How to Format Time Since Xxx E.G. "4 Minutes Ago" Similar to Stack Exchange Sites
Copy Array Items into Another Array
Programmatically Lighten or Darken a Hex Color (Or Rgb, and Blend Colors)
How to Quickly and Conveniently Disable All Console.Log Statements in My Code