1

how to sort highest value in this data using javascript?

data = [{a: [{num:31}, {num:10}]},{a: [{num:4}, {num:9}]},{a: [{num:5}, {num:9}]}]

Expected

data = [{a: [{num:31}]},{a: [{num:9}]},{a: [{num:9}]}]

I try like this but never happen :)

const data_sort = data.sort((a, b) => {
                                let abc
                                if (a.a.length > 0) {
                                    abc = a.a.sort((x, y) => x.a - x.a);
                                }
                                return a - b
                            })
0

3 Answers 3

4

    let data = [{a: [{num:31}, {num:10}]},{a: [{num:4}, {num:9}]},{a: [{num:5}, {num:9}]}]
    data = data.map(item => ({a:[item.a.sort((a, b) => b.num-a.num)[0]]})).sort((a, b) => b.a[0].num-a.a[0].num)

console.log(data)

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

Comments

0

Assuming this is the correct syntax, all you need is to map every item in the array to it's largest item, then sort that.

var data = [{
  a: [{num:31}, {num:10}]
}, {
  a: [{num:4}, {num:9}]
}, {
  a: [{num:6}, {num:11}]
}, {
  a: [{num:5}, {num:9}]
}];

var result = data.map(function(item) {
  return {
    a: [item.a.sort(function(a,b) {
      return a.num - b.num
    }).reverse()[0]]
  };
}).sort(function(a, b) {
  return a.a[0].num - b.a[0].num
}).reverse();
console.log(result)
.as-console-wrapper {
  max-height: 100% !important;
}

1 Comment

You could just exchange a.num - b.num in between and you won't need to reverse the array again.
0

Map and Reduce

const data = [{ a: [{ num: 31 }, { num: 10 }] }, { a: [{ num: 4 }, { num: 9 }] }, { a: [{ num: 5 }, { num: 9 }] }];
data.map((value) => {
  value.a = [
    {
      num: value.a.reduce((accumulatedValue, currentValue) => {
        return Math.max(accumulatedValue.num, currentValue.num);
      }),
    },
  ];
  return value;
});
console.log(data)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.