use*_*097 5 javascript arrays sorting
假设我有一个这样的数组:
var a = [94, "Neptunium", 2, "Helium", null, "Hypotheticalium", 64, "Promethium"];
Run Code Online (Sandbox Code Playgroud)
偶数数组索引与以下奇数索引相关联.换句话说,94去与"Neputunium"和2"氦"等我去如何排序基于偶数索引的数组,但请注意以下奇数索引值之后呢?所以我最终得到一个像这样的数组:
a = [null, "Hypotheticalium", 2, "Helium", 64, "Promethium", 94, "Neptunium"];
Run Code Online (Sandbox Code Playgroud)
注意:是的,我知道,知道,使用对象或ES6地图(或者甚至,在这种情况下,稀疏阵列的数字作为指标,如果空留出来)会更合适,但我只是探索这个来试验语言.谢谢你的帮助.
var grouped = [];
for (var i = 0; i < a.length; i += 2) {
grouped.push([a[i], a[i+1]]);
}
grouped.sort(function (a, b) { return a[0] - b[0]; });
Run Code Online (Sandbox Code Playgroud)
理想情况下,我建议您使用grouped此处的结构,因为将分组项组合在一起似乎更有意义,而不是依赖于隐式相邻索引.但是如果你需要再打开它:
var b = [];
for (var i = 0; i < grouped.length; i++) {
b.push.apply(b, grouped[i]);
}
Run Code Online (Sandbox Code Playgroud)
由于对下sort一个 JavaScript 引擎的调用顺序不一定是相同的(甚至在同一引擎的不同版本之间),因此您不能sort 直接在该数组上使用来执行您所描述的操作。
您可以使用map, filter, sort, 然后reduce:
var a = [94, "Neptunium", 2, "Helium", null, "Hypotheticalium", 64, "Promethium"];
a = a
.map(function(entry, index, array) {
return (index % 2 === 1) ? null : {
value: array[index + 1],
index: entry
};
})
.filter(function(entry) {
return entry != null;
})
.sort(function(left, right) {
return left.index - right.index; // Works even when either or both
// indexes are null, PROVIDED
// no non-null index is negative,
// because `null` will coerce to 0
})
.reduce(function(acc, entry) {
acc.push(entry.index, entry.value);
return acc;
}, []);
document.body.innerHTML = JSON.stringify(a);Run Code Online (Sandbox Code Playgroud)
这map让我们为成对的条目(和nulls)生成一个包含对象的数组。
该filter让我们去掉null秒。
该sort排序让我们。
这reduce让我们生成一个结果数组(因为我们不能map直接使用将一个条目映射到两个条目)。
如果您的偶数条目可能有负值,则sort回调必须以不同的方式处理事情,因为它将排序null在这些负索引之上(当然,除非这是您想要的)。
在 ES6 中更简洁一点:(在 Babel 的 REPL 上直播)
let a = [94, "Neptunium", 2, "Helium", null, "Hypotheticalium", 64, "Promethium"];
a = a
.map((entry, index, array) => {
return (index % 2 === 1) ? null : {
value: array[index + 1],
index: entry
};
})
.filter(entry => entry != null)
.sort((left, right) => left.index - right.index)
.reduce((acc, entry) => {
acc.push(entry.index, entry.value);
return acc;
}, []);
console.log(a);
Run Code Online (Sandbox Code Playgroud)