Since the order of calls is sortnot necessarily the same JavaScript engine for the next (or even between the revolutions of the same engine), you cannot sortdirectly use this array to do what you described.
You can use the map, filter, sort, and then 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;
})
.reduce(function(acc, entry) {
acc.push(entry.index, entry.value);
return acc;
}, []);
document.body.innerHTML = JSON.stringify(a);
Run codeHide resultmapallows us to create an array with objects for paired records (and nulls).
filterallows you to remove nulls.
sort allows you to sort.
reduceallows us to create an array of results (since we cannot use mapdirectly to match one record with two).
, 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);