-1

I need to sort some arrays inside an array.

For example:

let mainArr = [['john', 27, 'teacher'], ['Mary', 17, 'student'], ['Jane', 40, 'police']];

In this case I want to sort it by person's age, so the output would be:

let mainArrSorted = [['Mary', 17, 'student'], ['john', 27, 'teacher'], ['Jane', 40, 'police']];

Any sugestions?

NOTE: I don't want to implement array.sort() method.

Thank you in advance.

Mário Prada
  • 1,792
  • 1
  • 9
  • 13

1 Answers1

0

You can use array sort function:

let mainArr = [['john', 27, 'teacher'], ['Mary', 17, 'student'], ['Jane', 40, 'police']];
let mainArrSorted = mainArr.sort((a,b)=>(a[1]-b[1]));
console.log(mainArrSorted);
// mainArrSorted = [['Mary', 17, 'student'], ['john', 27, 'teacher'], ['Jane', 40, 'police']];

To prevent the source array will be sorted follow the destination array, you can use this code:

let mainArr = [['john', 27, 'teacher'], ['Mary', 17, 'student'], ['Jane', 40, 'police']];
let mainArrSorted = mainArr.slice();
mainArrSorted.sort((a,b)=>(a[1]-b[1]));
console.log(mainArrSorted); 
// mainArrSorted = [['Mary', 17, 'student'], ['john', 27, 'teacher'], ['Jane', 40, 'police']];

Or if you don't want array sort, you can use this code:

let mainArr = [['john', 27, 'teacher'], ['Mary', 17, 'student'], ['Jane', 40, 'police']];
let mainArrSorted = mainArr.slice();
for(let i=0;i<mainArrSorted.length-1;i++){
    for(let j=i+1;j<mainArrSorted.length;j++){
        if(mainArrSorted[i][1]>mainArrSorted[j][1]){
            let temp = mainArrSorted[i];
            mainArrSorted[i] = mainArrSorted[j];
            mainArrSorted[j] = temp;
        }
    }
}
console.log(mainArrSorted);
protoproto
  • 2,081
  • 1
  • 13
  • 13