2

I got a question, and would be really grateful if someone could explain to me in pseudo code how do I solve it

So here we go, I have an object like this

const obj = {
     'key1': [],
     'key2': [val1, val2],
     'key3': [],
     'key4': [val3]
     }

I need to remove the keys which contain an empty array, in this case key1 and key3, and then return a new object without the keys that contained the empty array. Im trying to figure this out on my own, but I'm still a JS newbie.

3 Answers3

2

It could be done by using the following actions:

  • use Object.entries() method to return an array of a given object's own enumerable string-keyed property
  • then use reduce() method to iterate through result of Object.entries. At each iteration, you are making a decision whether key_x contains array with length > 0

So the code looks like this:

const result = Object.entries(obj).reduce((a, [k,v])=> {
    if (v.length > 0) {
      a[k] = v;
    }
    return a;
},{})

An example:

const obj = {
     'key1': [],
     'key2': ['val1', 'val2'],
     'key3': [],
     'key4': ['val3']
     };

  const result = Object.entries(obj).reduce((a, [k,v])=> {
    if (v.length > 0) {
      a[k] = v;
    }
    return a;
  },{})

  console.log(result);
StepUp
  • 36,391
  • 15
  • 88
  • 148
  • Do you know how to do this in TS? When I try to set the key value on the object within in the reducer I get the following error: `Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature with a parameter of type 'string' was found on type '{}'.` – Woww Jun 28 '22 at 20:27
  • 1
    @Woww [Try this approach](https://stackoverflow.com/a/72284411/1646240) – StepUp Jun 29 '22 at 03:25
1

You could achieve this using simple filter and map. Filter out where array length is not zero and map it to actual object.

const obj = {
  "key1": [],
  "key2": [1, 2],
  "key3": [],
  "key4": [3]
};

const newArray = Object.keys(obj)
  .filter(i => obj[i].length)
  .map(j => ({[j]: obj[j]}));

console.log(newArray);
Ashish Modi
  • 7,529
  • 2
  • 20
  • 35
-2

Hint, I would use Object.entries to get key - value pair and then use reduce on the array. Hope that this helps :)