0

Here is my code:

let originalFloorsArr = {
  '10': [1,2,3],
  '11':[1,2,3],
  '13': [1,2,3,4]
}

let reversedFloorsArr = {};
Object.entries(originalFloorsArr).map(([key, item], i) => {
  reversedFloorsArr[key] = Object.keys(item).sort(
    (a, b) => item[b] - item[a]
  );
});

console.log("originalFloorsArr", originalFloorsArr);
console.log("reversedFloorsArr", reversedFloorsArr);

In this example, instead of reutning 3,2,1 for index 10 it is returning 2,1,0. However, there is no such value like 0 on originalFloorsArr[10]

2 Answers 2

3

That is because you get the keys of the inner arrays, while you need the values. So replace

Object.keys(item).sort(
    (a, b) => item[b] - item[a]
);

with

Object.values(item).sort(
    (a, b) => b - a
);
Sign up to request clarification or add additional context in comments.

Comments

2
let originalFloorsArr = {
    '10': [1,2,3],
    '11':[1,2,3],
    '13': [1,2,3,4]
}

  
for(let key in originalFloorsArr) { 
   originalFloorsArr[key].reverse()
}

console.log(originalFloorsArr['10']) //returns [3,2,1]

To reverse each array value in each property, you can use the Object for (let key in obj) method to iterate through the object, then reverse the array using the array reverse() method.

2 Comments

This would only work if the elements in the arrays were in order.
Oh yeah, that's right. Using .sort() is the best solution then. Thank you Andy

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.