【问题标题】:Sorting nested array based on second value in the inner array in Javascript [duplicate]基于Javascript内部数组中的第二个值对嵌套数组进行排序[重复]
【发布时间】:2016-10-10 06:39:09
【问题描述】:

我正在编写一个脚本,在该脚本中,我必须根据内部数组的第二个元素对数组的 arr 进行排序。例如下面我提到的数组:

var newInv = [
    [2, "Hair Pin"],
    [3, "Half-Eaten Apple"],
    [67, "Bowling Ball"],
    [7, "Toothpaste"]
];

我想根据内部数组中的所有字符串值对该数组进行排序。所以结果应该是:

var result = [
    [67, "Bowling Ball"],
    [2, "Hair Pin"],
    [3, "Half-Eaten Apple"],
    [7, "Toothpaste"]
];

为此,我编写了以下脚本: 有没有其他方法可以做同样的事情?可能没有创建对象?

function arraySort(arr) {

  var jsonObj = {};
  var values = [];
  var result = [];
  for (var i = 0; i < arr.length; i++) {
    jsonObj[arr[i][1]] = arr[i][0];

  }
  values = Object.keys(jsonObj).sort();

  for (var j = 0; j < values.length; j++) {
    result.push([jsonObj[values[j]], values[j]]);
  }
  return result;
}

var newInv = [
  [2, "Hair Pin"],
  [3, "Half-Eaten Apple"],
  [67, "Bowling Ball"],
  [7, "Toothpaste"]
];


console.log(arraySort(newInv));

【问题讨论】:

  • “没有创建 json 对象” - 你还没有创建一个“JSON 对象”(there's no such thing),你已经创建了一个“对象”。

标签: javascript arrays sorting


【解决方案1】:

你可以使用Array#sort

sort() 方法就地对数组的元素进行排序并返回该数组。排序不一定是stable。默认排序顺序是根据字符串 Unicode 代码点。

String#localeCompare

localeCompare() 方法返回一个数字,指示引用字符串是在排序顺序之前还是之后或与给定字符串相同。

var newInv = [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]];
  
newInv.sort(function (a, b) {
    return a[1].localeCompare(b[1]);
});

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

【讨论】:

  • 感谢您的快速解决方案和精彩的解释。真的很有帮助。
【解决方案2】:

当然,像这样,使用Arraysort()方法:

 newInv.sort((a, b) => a[1].localeCompare(b[1]));

这是一个sn-p:

var newInv = [
    [2, "Hair Pin"],
    [3, "Half-Eaten Apple"],
    [67, "Bowling Ball"],
    [7, "Toothpaste"]
];

newInv.sort((a, b) => a[1].localeCompare(b[1]));

console.log(newInv);

【讨论】:

  • 注意:这是 ES6 语法
【解决方案3】:

sort outer array based on values in inner array, javascript 的副本 在这里你会找到几个答案,比如我自己的

var arr = [.....]
arr.sort((function(index){
    return function(a, b){
        return (a[index] === b[index] ? 0 : (a[index] < b[index] ? -1 : 1));
    };
})(2)); // 2 is the index

按索引 2 排序

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-30
    • 2011-09-25
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    • 2014-04-06
    相关资源
    最近更新 更多