Skip to content

Commit 2577848

Browse files
author
Devendra Parmar
committed
Solved the two questions of the JavaScript
1. Create an object composed of the properties given in the function 2. Filter an array of objects based on condition given by the function
1 parent 71f9807 commit 2577848

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// Write a JavaScript program to create an object composed of the properties the given function returns truthy for. The function is invoked with two arguments: (value, key).
2+
3+
const pickBy = (obj, fn) => {
4+
return Object.keys(obj)
5+
.filter((k) => fn(obj[k], k))
6+
.reduce((acc, key) => ((acc[key] = obj[key]), acc), {});
7+
};
8+
9+
console.log(pickBy({ a: 1, b: "2", c: 3 }, (x) => typeof x === "number"));
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Write a JavaScript program to filter an array of objects based on a condition while also filtering out unspecified keys.
2+
3+
const reducedFilter = (data, keys, fn) => {
4+
return data.filter(fn).map((el) =>
5+
keys.reduce((acc, key) => {
6+
acc[key] = el[key];
7+
return acc;
8+
}, {})
9+
);
10+
};
11+
12+
const data = [
13+
{
14+
id: 1,
15+
name: "Darshan",
16+
age: 22,
17+
},
18+
{
19+
id: 2,
20+
name: "Devendra",
21+
age: 23,
22+
},
23+
];
24+
25+
console.log(reducedFilter(data, ["id", "name"], (item) => item.age > 22));

0 commit comments

Comments
 (0)