2017-02-28 111 views
0

此問題涉及我的算法以及它爲什麼不起作用。更具體地說,我想知道如何改進以做我想做的事情。這就是爲什麼它與建議的重複問題不同。基於屬性值對對象數組排序(int)

我想創建一個函數,它基於屬性值(int),他們都共同共享,「indexFound」分類對象的數組。正如你可能會懷疑的那樣,我試圖在數組的開頭放置一個indexFound值較低的元素。

function organizeTokens(list) { 
    for (i = 0; i < list.length - 1; i++) { 
     if (list[i].indexFound < list[i + 1].indexFound) { 
      // do nothing 
     } else if (list[i].indexFound > list[i + 1].indexFound) { 
      var tempVal = list[i]; 
      list[i] = list[i + 1]; 
      list[i + 1] = tempVal; 
     } else { 
     // should not happen unless we are comparing the same token 
     } 
    } 
}; 

既然這樣,當我給它的對象數組這個代碼不進行任何差別。這些元素仍然沒有按照他們應該的順序排列。我以正確的方式接近這個嗎?我錯過了明顯的東西嗎?

編輯:-------------------------------------------- -----------------------

示例輸入:organizTokens([{value:「if」,indexFound:7},{value:「a 」,indexFound:0}])

預期輸出:[{值: 「一個」,indexFound:0},{值: 「如果」,indexFound:7}]

實際輸出:[{值:「if」,indexFound:7},{value:「a」,indexFound:0}]

+1

你試過'Array.prototype.sort'嗎?或者你想自己算法解決這個問題? –

+0

我沒有。我現在檢查文檔。我正在尋找最高效,最理想的最簡單的方法 - 因爲它只是我正在構建的Lexer的巨型機器中的一個小型齒輪。 – Streamer

+0

你能發表一個數據輸入的例子,預期的輸出和你真的得到的輸出嗎? – zer00ne

回答

3

你可以使用Array.prototype.sort(),並定義一個比較函數:的

function compareIndexFound(a, b) { 
    if (a.indexFound < b.indexFound) { return -1; } 
    if (a.indexFound > b.indexFound) { return 1; } 
    return 0; 
} 

list.sort(compareIndexFound); 

簡單/簡潔版本比較上面的功能:

function compareIndexFound(a, b) { 
    return a.indexFound - b.indexFound; 
} 

使用ES6:

list.sort((a, b) => a.indexFound - b.indexFound); 

您可以定義自己的sortBy功能:

function sortBy(arr, prop) { 
    return arr.sort((a, b) => a[prop] - b[prop]); 
} 

sortBy(list, 'indexFound'); 
+0

在我的情況下,我怎麼稱呼它? a和b都等於相同的標記List嗎?像這樣?:list.sort(compareIndexFound(tokenList,tokenList))? – Streamer

+0

編輯:無所謂。我知道了。謝謝您的幫助。這比我想要做的要簡單得多。 – Streamer

1

您可以使用JavaScript的內置排序:

list.sort(function (l, r) { 
    return l.indexFound - r.indexFound; 
}); 

如果你使用像lodash實用或下劃線,他們有一個排序功能 這是更簡單:

var sorted = _.sortBy(list, 'indexFound'); 

例子:

var list = [ 
 
    { indexFound: 9 }, 
 
    { indexFound: 3 }, 
 
    { indexFound: 17 }, 
 
    { indexFound: 1 } 
 
]; 
 

 
var sorted = _.sortBy(list, 'indexFound'); 
 

 
console.log(sorted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

-1

使用帶有自定義回調函數的JS排序方法。像這樣:

list.sort(function (a, b) { 
    return a.indexFound - b.indexFound; 
}); 

這將按升序排列(從低到高)。