-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.

4
  • 1
    looks like you are sorting by the age(assuming that is what number is in each sub array) of each array. you could sort by [i][1] ? Commented Nov 5, 2018 at 22:18
  • 2
    you could sort it as you would sort an array with single items. Commented Nov 5, 2018 at 22:18
  • 2
    What did you try so far? Commented Nov 5, 2018 at 22:21
  • 1
    You would sort it like you would sort an array of any objects, by their [1] property. Commented Nov 5, 2018 at 22:21

1 Answer 1

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);

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

2 Comments

you do realise you've also sorted mainArr - which may not be what is required
You should use the builtin-functions (sort), it will quicker than the another function that you made!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.