Filter Array of Objects by Multiple Properties and Values

Filter array of objects by multiple properties and values

You can do it with Array.filter

var data = [{    "id": 1,    "term_id": 5,    "type": "car"  },  {    "id": 2,    "term_id": 3,    "type": "bike"  },  {    "id": 3,    "term_id": 6,    "type": "car"  }];
var result = data.filter(function(v, i) { return ((v["term_id"] == 5 || v["term_id"] == 6) && v.type == "car");})
console.log(result)

Filter array of objects by multiple values

You should call searchTerms.includes on obj.state and not the other way around. So it becomes:

let result = arr.filter(obj => searchTerms.includes(obj.state));

Which means filter out objects that have thier state property included in the array searchItems.

Example:

const arr = [{'city': 'Atlanta', 'state': 'Georgia'}, {'city': 'Chicago', 'state': 'Illinois'}, {'city': 'Miami', 'state': 'Florida'}];
const searchTerms = ['Georgia', 'Florida'];
let result = arr.filter(obj => searchTerms.includes(obj.state));
console.log(result);

Filter array of objects with nested objects by multiple properties

Along with the song title you also need to check the same condition with the values of lyrics object. You can get values of lyrics object by passing object to Object.values(). And with Array.some() you can evaluate if there is any element satisfying condition. As Array.some() returns a boolean it will make it easy to check.

fix would be.

const songs = [
{
"createdAt": {
"seconds": 1654000036,
"nanoseconds": 204000000
},
"lyrics": {
"liryc-1-b": "Some example lyrics verse 1",
"liryc-1-a": "Some example lyrics verse 2"
},
"category": "maculele",
"title": "asdasd"
},
{
"category": "corridos",
"createdAt": {
"seconds": 1653936021,
"nanoseconds": 438000000
},
"lyrics": {
"liryc-1-b": "lorem ipsum dolor lorem ipsum dolor lorem ipsum dolor lorem ipsum dolor lorem ipsum dolor lorem ipsum dolor ",
"liryc-1-a": "lorem ipsum dolor lorem ipsum dolor lorem ipsum dolor lorem ipsum dolor lorem ipsum dolor lorem ipsum dolor lorem ipsum dolor lorem ipsum dolor lorem ipsum dolor lorem ipsum dolor "
}
}
]

const query = 'dolor';

songs.filter(song => song.title?.toLowerCase().includes(query.toLowerCase()) || Object.values(song.lyrics)?.some(l => l.toLowerCase().includes(query.toLowerCase()))).map(r => console.log(r));

javascript filter array multiple conditions

You can do like this

var filter = {  address: 'England',  name: 'Mark'};var users = [{    name: 'John',    email: 'johnson@mail.com',    age: 25,    address: 'USA'  },  {    name: 'Tom',    email: 'tom@mail.com',    age: 35,    address: 'England'  },  {    name: 'Mark',    email: 'mark@mail.com',    age: 28,    address: 'England'  }];

users= users.filter(function(item) { for (var key in filter) { if (item[key] === undefined || item[key] != filter[key]) return false; } return true;});
console.log(users)

How to filter an array of objects based on multiple properties in JavaScript/Typescript?

You could just use a lookup table, this is in O(n) runtime.

Basically iterate once through the array, remember for each valid name the highest version you saw, and then use that table as a filter for the original array.

const lookup = {} as Record<string, {name: string, version: number, invalid: boolean}>;
arr.forEach((it) => {
const stored = lookup[it.name];
if (stored) {
if (!it.invalid && it.version > stored.version) {
lookup[it.name] = it;
}
} else {
lookup[it.name] = it;
}
})

const filtered = arr.filter((it) => {
const stored = lookup[it.name];
const result = !it.invalid && it.version === stored.version;
if (result) { //if no duplicates wanted
delete lookup[it.name];
}
return result;
});

Filter multiple array object with multiple property

You can use filter to search for the data. Use reduce to construct the keys.

Note: filter returns an array of matched elements. If you prefer the first match only, you can use find

const data = [
{ id: 1, data: { name: "sample1", address:{ cat: "business" } } },
{ id: 2, data: { name: "sample2", address:{ cat: "office" } } },
{ id: 3, data: { name: "sample3", address:{ cat: "office" } } },
{ id: 4, data: { name: "sample4", address:{ cat: "office" } } },
{ id: 5, data: { name: "sample5", address:{ cat: "home" } } },
{ id: 6, data: { name: "sample6", address:{ cat: "home" } } }
]

const filter = (collection, keys, value) =>
collection.filter(o => keys.reduce((c, v) => c[v] || {}, o) === value)
const result = filter(data, ["data", "address", "cat"], "business")

console.log(result)

Filtering an array by multiple property values

You could check if query is an array and/or the value is an array and check accordingly.

function nestedFilter(data, query) {
const
filters = Object.entries(query);

return data.filter(o => filters.every(([k, v]) => Array.isArray(v)
? Array.isArray(o[k])
? v.some(s => o[k].includes(s))
: v.includes(o[k])
: Array.isArray(o[k])
? o[k].includes(v)
: o[k] === v
));
}

const
cars = [{ name: "BMW X5", topsales: ["USA", "China", "Russia"], maxspeed: 250, users: ["teenage", "ladies", "mens"] }, { name: "Volkswagen Touareg", topsales: ["USA", "Germany"], maxspeed: 240, users: ["teenage", "mens", "old mens"] }],
query = { topsales: ["USA", "China"], users: "teenage" };

console.log(nestedFilter(cars, query));

How to filter an array of object by multiple property values?

let articles = [{  title: 'title 1',  tags: ["JavaScript", "ES6"],  category: "JavaScript"}, {  title: 'title 2',  tags: ["React", "TypeScript"],  category: "React"}, {  title: 'title 3',  tags: ["JavaScript", "Inheritance", "Prototype"],  category: "JavaScript"}]
let search = "ES6";let search2 = "JavaScript";
let result = articles.filter(((data) => [search, search2].every((tag) => data.tags.includes(tag))))
console.log(result)

Filtering an array of objects with multiple filter conditions

Use Object.entries() on filters to get an array of [key, values] pairs. Iterate the pairs with Array.every(), and check that each pair includes the value of the current object.

const fn = (arr, filters) => {
const filtersArr = Object.entries(filters)

return arr.filter(o =>
filtersArr.every(([key, values]) =>
values.includes(o[key])
)
)
}

const users = [{"name":"Mark","location":"US","job":"engineer"},{"name":"Mark","location":"US","job":"clerk"},{"name":"Angela","location":"Europe","job":"pilot"},{"name":"Matthew","location":"US","job":"engineer"}]

const filters = {
name: ["Mark", "Matthew"],
location: ["US"],
job: ["engineer"]
}

const result = fn(users, filters)

console.log(result)


Related Topics



Leave a reply



Submit