0

How do I sort array so that this output

[ [ '6.9', '14.5' ], [ '22.2', '28.9' ] ]

is sorted primarily with x value so 6.9 and 22.5 in the above example and secondarily with y axis, 14.5 and 28.9 in the above example.

this is my code currently to get the output.

const mySet = uniqueArray4(x_y_total);

    mySet.forEach(element => {
        let sumx = 0, sumy = 0;
            for(let i = 0; i < element.length; i++) {
                sumx += element[i][0]/element.length;
                sumy += element[i][1]/element.length;
            }
            
            answer.push([sumy.toFixed(1), sumx.toFixed(1)]);
            });
        
    answer.forEach(element => {
        finalanswer.push(element);
    })

Quite new to js, I searched through google but it's been quite difficult as to how should I implement this.

  • 1
    This sounds like a toy question, but I'll bite. As a pro, I'd use the javascript sorting mechanisms: https://stackoverflow.com/a/39583521/269694 – Nitrodist Dec 02 '21 at 05:35

1 Answers1

1

You can sort based on the 1st entry, and then on the 2nd entry, something like:

// Sorting on 1st param
answer.sort((a,b) => a[0] - b[0]);

// Sorting on 2nd param given then 1st param is sorted, if not, return 0
answer.sort((a,b) => a[0] < b[0] ? a[1] - b[1] : 0);
Kanishk Anand
  • 1,686
  • 1
  • 7
  • 16