2017-06-18 45 views
1

後值I具有下一個陣列:如何保持數組索引>排序以JavaScript

var a = [0, 2, 1, 3]; 

凡本數組索引>值對是:

0 = 0,1 = 2,2 = 1,3 = 3

什麼是最簡單和最優雅的方式來保持數組索引號後對數組進行排序。後排序()指數>值對應該是這樣的:

0 = 0,2 = 1,1 = 2,3 = 3

..但我應該能夠顯示這些排序值。問題是,數組無法通過跳轉索引位置0,2,1,3來列出,但僅限於0,1,2,3。

可以以某種方式創建一個新數組,其數組值將是那些新的索引位置,並且然後對這個新數組進行排序,但要記住以前的索引>值對。

雖然聽起來很簡單,但我找不到解決方案。

謝謝

P.S.我實際上想按數組中包含的短語中的單詞之間的空格數進行排序。然後我想按照空格的數量排序(首先是大多數詞組)。

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 
} 

回答

0

如果您想通過一些平凡的排序,通過回調sort

input.sort(function(a,b) { 
    // b - a for descending order 
    return b.split(" ").length - a.split(" ").length; 
}); 
+0

嘿@尼婭,這個作品完美!而且它也很簡單。不幸的是,由於我的新名聲,我不能給你我的投票。非常感謝。 – Dan

3

你可以使用Sorting with map一個新的陣列保持原有指標和值。

// the array to be sorted 
 
var list = [0, 2, 1, 3]; 
 

 
// temporary array holds objects with position and sort-value 
 
var mapped = list.map(function(el, i) { 
 
    return { index: i, value: el }; 
 
}) 
 

 
// sorting the mapped array containing the reduced values 
 
mapped.sort(function(a, b) { 
 
    return a.value - b.value; 
 
}); 
 

 
// container for the resulting order 
 
var result = mapped.map(function(el){ 
 
    return list[el.index]; 
 
}); 
 

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

+0

感謝您的善意幫助。 – Dan