Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
37
rated 0 times [  42] [ 5]  / answers: 1 / hits: 39785  / 7 Years ago, sun, july 9, 2017, 12:00:00

I have an array of objects and I'd like to filter it based on the objects property values. I'd like to filter it by different properties, so it needed to be dynamic. For this I have an input field where I type and then filter the array. So, let's say I have these 2 different arrays:



const array_one = [
{id: 1, code: 'ABC123', name: 'John'},
{id: 2, code: 'DEF456', name: 'Stew'},
// ...
];

const array_two = [
{id: 1, value: '012345', company: 'Company 01' },
{id: 2, value: '678910', company: 'Company 02' },
// ...
];


I want a function where I can filter the first array based on the name, also If I want to filter the second array, I want to filter it by the value.



For this, I built this function:



filterArray(array: Array<any>, fields: Array<any>, value: string) {
value = this.convertString(value);

array = array.filter((item) => {
fields.forEach(obj => {
if ( item[obj] ) {
const _newObj = this.convertString(item[obj]);
if ( _newObj.indexOf(value) !== -1 ) {
console.log(item);
return item;
}
}
});
});

return array;
}
// convertString() is just another function to replace accents, spaces, etc...


Then I call it like this:



filterArray(originalArray, ['name'], valueFromInput);

// or...
filterArray(originalArray, ['value'], valueFromInput);

// or even...
filterArray(originalArray, ['value', 'company'], valueFromInput);


But the array filtered is always returnin empty, even if the console inside the indexOf verification prints the correct object on the console.



What am I doing wrong here? Because it's filtering properly, I have manually checked it, but it doesn't add to the new filtered array.


More From » arrays

 Answers
8

You can iterate the fields using Array#some, and if one of them is equal to value return the item:





const array_one = [
{id: 1, code: 'ABC123', name: 'John'},
{id: 2, code: 'DEF456', name: 'Stew'}
];

const array_two = [
{id: 1, value: '012345', company: 'Company 01' },
{id: 2, value: '678910', company: 'Company 02' }
];

const filterArray = (array, fields, value) => {
fields = Array.isArray(fields) ? fields : [fields];

return array.filter((item) => fields.some((field) => item[field] === value));
};

console.log(filterArray(array_one, 'name', 'Stew'));

console.log(filterArray(array_two, ['id', 'company'], 2));

console.log(filterArray(array_two, ['id', 'company'], 'Company 02'));




[#57151] Friday, July 7, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gideons

Total Points: 197
Total Questions: 106
Total Answers: 108

Location: Moldova
Member since Sat, Jan 29, 2022
2 Years ago
;