排序后如何保持数组索引>值

Dan*_*Dan 4 javascript arrays sorting

在 javascript 中我有下一个数组:

var a = [0, 2, 1, 3];
Run Code Online (Sandbox Code Playgroud)

其中该数组索引>值对是:

0 = 0、1 = 2、2 = 1、3 = 3

在对数组进行排序后保留数组索引号的最简单和最优雅的方法是什么。sort() 之后索引>值对应该是这样的:

0 = 0、2 = 1、1 = 2、3 = 3

..但我应该能够显示这些排序值。问题是数组不能通过跳转索引位置 0, 2, 1, 3 来列出,而只能作为 0, 1, 2, 3。

我可以以某种方式创建一个新数组,其数组值将是那些新的索引位置,然后对这个新数组进行排序,但保留以前的索引>值对。

虽然听起来很简单,但我找不到解决方案。

谢谢

PS 我实际上想按数组中包含的短语中单词之间的空格数进行排序。然后我想显示按空格数排序的内容(首先是单词最多的短语)。

var input = ["zero", "here two spaces", "none", "here four spaces yes"];
var resort = [];
for (i = 0; i < input.length; i++) {
  var spaces = (input[i].split(" ").length - 1);
  resort.push(spaces); // new array with number of spaces list
}
Run Code Online (Sandbox Code Playgroud)

Nin*_*olz 5

您可以使用地图排序,该数组保留原始索引和值。

\n\n

\r\n
\r\n
// the array to be sorted\r\nvar list = [0, 2, 1, 3];\r\n\r\n// temporary array holds objects with position and sort-value\r\nvar mapped = list.map(function(el, i) {\r\n    return { index: i, value: el };\r\n})\r\n\r\n// sorting the mapped array containing the reduced values\r\nmapped.sort(function(a, b) {\r\n    return a.value - b.value;\r\n});\r\n\r\n// container for the resulting order\r\nvar result = mapped.map(function(el){\r\n    return list[el.index];\r\n});\r\n\r\nconsole.log(result);\r\nconsole.log(mapped);
Run Code Online (Sandbox Code Playgroud)\r\n
.as-console-wrapper { max-height: 100% !important; top: 0; }\xc2\xb4
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n