Skip to content

Commit 5680a34

Browse files
committed
Add solution #2705
1 parent 95fb8b2 commit 5680a34

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -407,6 +407,7 @@
407407
2677|[Chunk Array](./2677-chunk-array.js)|Easy|
408408
2695|[Array Wrapper](./2695-array-wrapper.js)|Easy|
409409
2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy|
410+
2705|[Compact Object](./2705-compact-object.js)|Medium|
410411
2715|[Timeout Cancellation](./2715-timeout-cancellation.js)|Easy|
411412
2721|[Execute Asynchronous Functions in Parallel](./2721-execute-asynchronous-functions-in-parallel.js)|Medium|
412413
2722|[Join Two Arrays by ID](./2722-join-two-arrays-by-id.js)|Medium|

solutions/2705-compact-object.js

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* 2705. Compact Object
3+
* https://leetcode.com/problems/compact-object/
4+
* Difficulty: Medium
5+
*
6+
* Given an object or array obj, return a compact object.
7+
*
8+
* A compact object is the same as the original object, except with keys containing falsy
9+
* values removed. This operation applies to the object and any nested objects. Arrays are
10+
* considered objects where the indices are keys. A value is considered falsy when
11+
* Boolean(value) returns false.
12+
*
13+
* You may assume the obj is the output of JSON.parse. In other words, it is valid JSON.
14+
*/
15+
16+
/**
17+
* @param {Object|Array} obj
18+
* @return {Object|Array}
19+
*/
20+
var compactObject = function(obj) {
21+
if (obj === null) return null;
22+
if (Array.isArray(obj)) return obj.filter(Boolean).map(compactObject);
23+
if (typeof obj !== 'object') return obj;
24+
25+
return Object.keys(obj).reduce((result, key) => {
26+
const value = compactObject(obj[key]);
27+
if (value) {
28+
result[key] = value;
29+
}
30+
return result;
31+
}, {});
32+
};

0 commit comments

Comments
 (0)