Javascript:如何对数组中的对象值进行排序?

时间:2022-05-29 15:27:13

I want sort a Array in JavaScript by value of object which is that array holding.

我想按对象的值对JavaScript中的数组进行排序也就是数组的值。

For example:

例如:

Input

输入

arr = [{id:[2, 'second']},{id:[8, 'eighth']},{id:[1, 'first']}]; 

My excepted output is:

我的除外的输出是:

sorted_arr = [{id:[8, 'eighth']},{id:[1, 'first']},{id:[2, 'second']}]; 

Note: Please give sort by alphabet

注:请按字母排序。

2 个解决方案

#1


3  

You can make a compare function like this which will do as require.

你可以做一个像这样的比较函数,它会按需要做。

arr.sort(function(a, b){
    return a["id"][0]-b["id"][0];
});

Suppose in case when both id's are equal, in that case if you want to do sorting on basis of your second parameter i.e first,second third then the code will be

假设当两个id相等时,如果你想根据第二个参数i排序。e第一,第二,第三,那么代码就是

arr.sort(function(a, b){
    if(a["id"][0]===b["id"][0])
    {   

        if(a["id"][1] < b["id"][1]) return -1;
        if(a["id"][1] > b["id"][1]) return 1;
        return 0;

    }
    return a["id"][0]-b["id"][0];
});

#2


2  

You can use sort()

您可以使用sort()

arr = [{
  id: [2, 'second']
}, {
  id: [4, 'fourth']
}, {
  id: [1, 'first']
}];

var sort = arr.sort(function(a, b) {
  return a.id[0] - b.id[0];
});

document.write('<pre>' + JSON.stringify(sort, null, 3) + '</pre>');

If you want to sort based on the word in array then you need to compare the values

如果您想基于数组中的单词进行排序,那么您需要比较这些值

arr = [{
  id: [2, 'second']
}, {
  id: [4, 'fourth']
}, {
  id: [1, 'first']
}];

var sort = arr.sort(function(a, b) {
  if (a.id[1] > b.id[1]) return 1;
  if (a.id[1] < b.id[1]) return -1;
  return 0;
});

document.write('<pre>' + JSON.stringify(sort, null, 3) + '</pre>');

#1


3  

You can make a compare function like this which will do as require.

你可以做一个像这样的比较函数,它会按需要做。

arr.sort(function(a, b){
    return a["id"][0]-b["id"][0];
});

Suppose in case when both id's are equal, in that case if you want to do sorting on basis of your second parameter i.e first,second third then the code will be

假设当两个id相等时,如果你想根据第二个参数i排序。e第一,第二,第三,那么代码就是

arr.sort(function(a, b){
    if(a["id"][0]===b["id"][0])
    {   

        if(a["id"][1] < b["id"][1]) return -1;
        if(a["id"][1] > b["id"][1]) return 1;
        return 0;

    }
    return a["id"][0]-b["id"][0];
});

#2


2  

You can use sort()

您可以使用sort()

arr = [{
  id: [2, 'second']
}, {
  id: [4, 'fourth']
}, {
  id: [1, 'first']
}];

var sort = arr.sort(function(a, b) {
  return a.id[0] - b.id[0];
});

document.write('<pre>' + JSON.stringify(sort, null, 3) + '</pre>');

If you want to sort based on the word in array then you need to compare the values

如果您想基于数组中的单词进行排序,那么您需要比较这些值

arr = [{
  id: [2, 'second']
}, {
  id: [4, 'fourth']
}, {
  id: [1, 'first']
}];

var sort = arr.sort(function(a, b) {
  if (a.id[1] > b.id[1]) return 1;
  if (a.id[1] < b.id[1]) return -1;
  return 0;
});

document.write('<pre>' + JSON.stringify(sort, null, 3) + '</pre>');