I am new to JS. I want to apply filter on array based on other arrays. For example : Filter data
array based on property names from colNames
and values from Values
array. The colNames
and Values
arrays can have any length (not always 2).
JavaScript
x
44
44
1
var data = [{
2
"name": "Tiger Nixon",
3
"position": "System Architect",
4
"salary": "320800",
5
"start_date": "2011/04/25",
6
"office": "Edinburgh",
7
"rating": "5421"
8
},
9
{
10
"name": "Garrett Winters",
11
"position": "Accountant",
12
"salary": "170750",
13
"start_date": "2011/07/25",
14
"office": "Tokyo",
15
"rating": "8422"
16
},
17
{
18
"name": "Garrett Winters",
19
"position": "Analyst",
20
"salary": "170750",
21
"start_date": "2011/07/25",
22
"office": "Tokyo",
23
"rating": "8422"
24
},
25
{
26
"name": "Ashton Cox",
27
"position": "Junior Technical Author",
28
"salary": "86000",
29
"start_date": "2009/01/12",
30
"office": "San Francisco",
31
"rating": "1562"
32
},
33
{
34
"name": "Cedric Kelly",
35
"position": "Senior Javascript Developer",
36
"salary": "433060",
37
"start_date": "2012/03/29",
38
"office": "Edinburgh",
39
"rating": "6224"
40
}
41
]
42
43
var colNames = ['name', 'position']
44
var Values = ['Garrett Winters', 'Accountant']
Expected Outcome
JavaScript
1
9
1
[{
2
"name": "Garrett Winters",
3
"position": "Accountant",
4
"salary": "170750",
5
"start_date": "2011/07/25",
6
"office": "Tokyo",
7
"rating": "8422"
8
}]
9
Advertisement
Answer
You could filter with the iteration of all keys and check with the values.
JavaScript
1
7
1
const
2
data = [{ name: "Tiger Nixon", position: "System Architect", salary: "320800", start_date: "2011\/04\/25", office: "Edinburgh", rating: "5421" }, { name: "Garrett Winters", position: "Accountant", salary: "170750", start_date: "2011\/07\/25", office: "Tokyo", rating: "8422" }, { name: "Garrett Winters", position: "Analyst", salary: "170750", start_date: "2011\/07\/25", office: "Tokyo", rating: "8422" }, { name: "Ashton Cox", position: "Junior Technical Author", salary: "86000", start_date: "2009\/01\/12", office: "San Francisco", rating: "1562" }, { name: "Cedric Kelly", position: "Senior Javascript Developer", salary: "433060", start_date: "2012\/03\/29", office: "Edinburgh", rating: "6224" }],
3
cols = ['name', 'position'],
4
values = ['Garrett Winters', 'Accountant'],
5
result = data.filter(o => cols.every((k, i) => o[k] === values[i]));
6
7
console.log(result);
JavaScript
1
1
1
.as-console-wrapper { max-height: 100% !important; top: 0; }