How to Use Array.Filter to Filter a Class Object Based on a Property

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 do i use array.filter to filter a class object based on a property?

This should work...

let males = people.filter({ $0.gender == .male })

You may need to make your enum conform to equatable to do this comparison.

The $0 is an unnamed parameter, you could also do..

let males = people.filter({ person in
return person.gender == .male
})

EDIT: I've just tested this and it does work without making the enum conform to equatable. I think you only need to do that when the enum takes parameters.

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 based on another array of object's property value?

let arr1 = [
{ key: "WIHUGDYVWJ", className: "science" },
{ key: "qwljdhkuqwdnqwdk", className: "english" },
{ key: "likubqwd", className: "robotics" },
{ key: "abcd", className: "history" }
];

let arr2 = [
{ key: "WIHUGDYVWJ", title: "math" },
{ key: "qwljdhkuqwdnqwdk", title: "english" },
{ key: "likubqwd", title: "robotics" }
];

// q1 answer
console.log(arr1.map(arr1Item => arr2.filter(arr2Item => arr1Item.className === arr2Item.title)).flat());

// q2 answer
console.log(arr1.filter(arr1Item => !arr2.some(arr2Item => arr2Item.title === arr1Item.className)));

Filter array of objects whose any properties contains a value

You could filter it and search just for one occurence of the search string.

Methods used:

  • Array#filter, just for filtering an array with conditions,

  • Object.keys for getting all property names of the object,

  • Array#some for iterating the keys and exit loop if found,

  • String#toLowerCase for getting comparable values,

  • String#includes for checking two string, if one contains the other.

function filterByValue(array, string) {    return array.filter(o =>        Object.keys(o).some(k => o[k].toLowerCase().includes(string.toLowerCase())));}
const arrayOfObject = [{ name: 'Paul', country: 'Canada', }, { name: 'Lea', country: 'Italy', }, { name: 'John', country: 'Italy' }];
console.log(filterByValue(arrayOfObject, 'lea')); // [{name: 'Lea', country: 'Italy'}]console.log(filterByValue(arrayOfObject, 'ita')); // [{name: 'Lea', country: 'Italy'}, {name: 'John', country: 'Italy'}]
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to filter model array based on specific property

try this

let filteredArray = self.originalArray.filter({($0.itemCategory.localizedCaseInsensitiveContains(searchText))!})

How to filter array of objects and get distinct based on a specific property

You have two tasks, filtering, and finding distinct items (practically: grouping).

So when we define two functions, one for filtering by a given property:

const filterByProp = 
(prop) =>
(value) =>
(items) =>
items.filter((item) => item[prop] === value);

and one for finding the distinct (in this case: each first item per value) by a given property:

const distinctByProp = 
(prop) =>
(items) =>
Object.values(items.reduce((group, item) => {
if (!group.hasOwnProperty(item[prop])) group[item[prop]] = item;
return group;
}, {}));

we can do

const onlyClassC = filterByProp("Class")("Class C");
const distinctByGroup = distinctByProp("Group");

const filtered = distinctByGroup(onlyClassC(result));

and get filtered as:

[
{
"Class": "Class C",
"Group": "Group A",
"Value": 1
},
{
"Class": "Class C",
"Group": "Group B",
"Value": 10
}
]

If you want the last item per distinct group instead of the first, remove the if (!group.hasOwnProperty(item[prop])) from distinctByProp.

const filterByProp = 
(prop) =>
(value) =>
(items) =>
items.filter((item) => item[prop] === value);

const distinctByProp =
(prop) =>
(items) =>
Object.values(items.reduce((group, item) => {
if (!group.hasOwnProperty(item[prop])) group[item[prop]] = item;
return group;
}, {}));

// -----------------------------------------------------------------------
const onlyClassC = filterByProp("Class")("Class C");
const distinctByGroup = distinctByProp("Group");

// -----------------------------------------------------------------------
var result = [
{
"Class": "Class C",
"Group": "Group A",
"Value": 1
},
{
"Class": "Class C",
"Group": "Group A",
"Value": 2
},
{
"Class": "Class A",
"Group": "Group B",
"Value": 2
},
{
"Class": "Class C",
"Group": "Group B",
"Value": 10
}
];

const filtered = distinctByGroup(onlyClassC(result));
console.log(filtered);

Javascript filter array of objects by class

Using instanceof

The instanceof operator tests to see if the prototype property of a
constructor appears anywhere in the prototype chain of an object. The
return value is a boolean value.

let arr = array.filter(foo => foo instanceof foo1)