File tree 2 files changed +33
-0
lines changed
2 files changed +33
-0
lines changed Original file line number Diff line number Diff line change 407
407
2677|[ Chunk Array] ( ./2677-chunk-array.js ) |Easy|
408
408
2695|[ Array Wrapper] ( ./2695-array-wrapper.js ) |Easy|
409
409
2703|[ Return Length of Arguments Passed] ( ./2703-return-length-of-arguments-passed.js ) |Easy|
410
+ 2705|[ Compact Object] ( ./2705-compact-object.js ) |Medium|
410
411
2715|[ Timeout Cancellation] ( ./2715-timeout-cancellation.js ) |Easy|
411
412
2721|[ Execute Asynchronous Functions in Parallel] ( ./2721-execute-asynchronous-functions-in-parallel.js ) |Medium|
412
413
2722|[ Join Two Arrays by ID] ( ./2722-join-two-arrays-by-id.js ) |Medium|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments