tittimous
tittimous

Reputation: 39

Sort arrays based on specific field

Say I have the following arrays

[[['kodak'], 1],
[['It\'s', 'a', 'kodak'. 'moment'], 4],
[['It\'s', 'a', 'kodak'], 3]]

and I want to sort the inner arrays by the second parameter of each inner array from least to greatest so:

[[['It's', 'a', 'kodak'. 'moment'], 4],
[['It's', 'a', 'kodak'], 3],
[['kodak'], 1]];

Any suggestions? I understand I can just sort by length, but I do need the data in this format.

Upvotes: 0

Views: 82

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386654

Instead of the given answers, I suggest to use a comparison mechanique which utilize the full range of return value of the comparing function of Array#sort. In this case, the sort method expect values smaller than zero, zero or values greater than zero, which reflects the relation between to items of the array.

The proposed a[1] < b[1] or a[1] > b[1] never returns a value of -1. that means, a simply sorted reversed array is not necessary equal to the array sorted with swiched parameters.

This solution takes the full range of needed return value and is in this kind symetrically as aboved mentioned.

var array = [[['kodak'], 1], [['It\'s', 'a', 'kodak', 'moment'], 4], [['It\'s', 'a', 'kodak'], 3]];

array.sort(function (a, b) {
    return b[1] - a[1];
});

console.log(array);

Upvotes: 1

Kamil Mikosz
Kamil Mikosz

Reputation: 11

var arr = [[['It\'s', 'a', 'kodak', 'moment'], 4],
[['It\'s', 'a', 'kodak'], 3],
[['kodak'], 1]];

arr.sort(function(a, b){
    return a[1]>b[1]
})

Upvotes: 0

Diego
Diego

Reputation: 816

It will always sort using the second position of the array.

const array = [[['kodak'], 1], [['It\'s', 'a', 'kodak', 'moment'], 4], [['It\'s', 'a', 'kodak'], 3]]

const result = array.sort((a, b) => a[1] < b[1])

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 2

Related Questions