简体   繁体   中英

Sort objects inner array and return object

If I have a object like this:

const foo = {
    title: 'Bar',
    numbers: [1, 4, 3, 2],
}

I would like to sort foo.numbers and return the new foo object.

To sort the array is easy foo.numbers.sort((a, b) => b - a)

but this returns just the array.

Is there anyway to return the parent object?

for example:

const newFoo = sortFooNumbers(foo);

console.log(newFoo);
---
{
    title: 'Bar',
    numbers: [1, 2, 3, 4],
}
const foo = {
    title: 'Bar',
    numbers: [1, 4, 3, 2],
}

function sortfoo(obj){
    obj.numbers.sort((a, b) => b - a)
    return obj
}

sortfoo(foo)
foo.numbers = foo.numbers.sort((a, b) => b - a)

You now have an updated foo with the sorted array. I'm assuming this is what you want.

Then you probably need to clone the object too:

const foo = {
  title: 'Bar',
  numbers: [1, 4, 3, 2],
};

function sortFoo(foo){
  const cloned = JSON.parse(JSON.stringify(foo));
  cloned.numbers.sort((a,b)=>a-b);
  return cloned;
}

const newFoo = sortFoo(foo);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM