-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFilterByValue.js
More file actions
47 lines (42 loc) · 1 KB
/
FilterByValue.js
File metadata and controls
47 lines (42 loc) · 1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const filterObject = (arr, aggVal) => {
if (typeof aggVal === "number") {
return arr[aggVal];
}
// // for (const entry of arr){
// // for (const [key, value] of Object.entries(entry)) {
// // } second approach
// }
const values = Object.values(arr);
const obj = [];
for (let i = 0; i < values.length; i++) {
const keys = Object.keys(values[i]);
let flg = 0;
for (let j = 0; j < keys.length; j++) {
if (arr[i][keys[j]] === aggVal) {
flg = 1;
break;
}
}
if (flg == 1) {
obj.push(values[i]);
}
}
if (obj.length === 0) {
return -1;
}
return obj;
};
const arr = [
{ name: "Amir", id: "1" },
{ name: "Samlan", id: "2" },
{ name: "Shahrukh", id: "0" },
];
console.log(filterObject(arr, 0));
console.log(filterObject(arr, "Amir"));
console.log(filterObject(arr, "0"));
console.log(filterObject(arr, "-1"));
// Output:
// { name: "Amir", id: "1" }
// { name: "Amir", id: "1" }
// { name: "Shahrukh", id: "0" }
// undefined