0

Here is the code:

    let bucket = [[],[],[],[],[],[],[],[],[],[]];

    bucket = {...Object.keys(bucket)
                       .sort((a,b) => b-a)
                       .filter(key => key > 0)
                       .map(key => '-'+key), 
              ...bucket};

   console.log(bucket);

Problem: the first line of code is not adding the negative keys of the original bucket object into the object, with all properties (keys) having empty arrays as their corresponding value.

Bucket only shows its original properties and values after this line of code is evaluated

How can I get this to work?

1 Answer 1

1

The Array.map() creates an array of strings with your negative keys, and they are overwritten when you spread the bucket array. Instead create pairs of [new key, []] convert to an object with Object.fromEntries(), and then spread them:

const bucket = [[],[],[],[],[],[],[],[],[],[]];

const result = {
  ...Object.fromEntries(
    Object.keys(bucket)
      .filter(key => key > 0)
      .sort((a, b) => b-a)
      .map(key => [-key, []])
  ),
  ...bucket};

console.log(result);

Sign up to request clarification or add additional context in comments.

1 Comment

Ok... I see now, so my array needs to be converted back to an object and then be spread out which I did not successfully do. I have now a new method I need to use regularly when necessary, the fromEntries method. I also incorrectly did not specify the empty value for key. Can this be done without a pair of array values, but more like bracket of [-key] alone with a corresponding property? Please suggest. Thank you so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.