2014-03-31 77 views
1

我有一個數組是這樣的:JS:把元素陣列開始條件

[ 
    {id: 5, attr: 99}, 
    {id: 7, attr: null}, 
    {id: 2, attr: 8}, 
    {id: 9, attr: 3}, 
    {id: 4, attr: null} 
] 

什麼是最有效的把所有物品與attr === null在數組的開頭,在不改變的順序數組中的其他元素? (例如,我需要按順序進行:7,4,5,2,9(7和4的順序無關緊要,但是5,2,9的順序絕不能改變)。

簡單撥弄測試代碼:http://jsfiddle.net/8GEPC/

+0

請評論,如果我沒有解釋清楚的東西不夠。 – Dalius

+0

你真的需要有最有效的方法嗎?它可能無所謂...看看[這些答案](http://stackoverflow.com/questions/979256/sorting-an-array-of-javascript-objects) – Laoujin

+0

效率並不重要,我只是喜歡儘可能快地使所有東西:) – Dalius

回答

2
var arr = [ 
    {id: 5, attr: 99}, 
    {id: 7, attr: null}, 
    {id: 2, attr: 8}, 
    {id: 9, attr: 3}, 
    {id: 4, attr: null} 
] 

var nulls = arr.filter(function(a){return a.attr === null}); 
var notnulls = arr.filter(function(a){return a.attr !== null}); 

nulls.concat(notnulls); 

// outputs [{"id":7,"attr":null},{"id":4,"attr":null},{"id":5,"attr":99},{"id":2,"attr":8},{"id":9,"attr":3}] 

,這裏是用一個解決方案減少:

var sorted = arr.reduce(function(output, element) { 
    if (element.attr === null) 
    output.unshift(element); 
    else 
    output.push(element); 
    return output 
}, []); 
console.log(sorted); 
+0

Reduce不起作用 – Dalius

+0

您使用的是IE8嗎? –

+0

只是忘了做arr = arr.reduce。接受此爲減少(排序看起來太醜,對不起) – Dalius

1

搶的對象,其中attr === null

var withNull = arr.filter(function (el) { return el.attr === null }); 

抓取對象attr !== null

var withVal = arr.filter(function (el) { return el.attr !== null }); 

將'null array'添加到'values數組'的前面。

withVal.unshift.apply(withVal, withNull); 

Fiddle

3

能使用內置在需要兩個迴路或一個while循環找元素並刪除它們過濾方法。

var x = [ 
    {id: 5, attr: 99}, 
    {id: 7, attr: null}, 
    {id: 2, attr: 8}, 
    {id: 9, attr: 3}, 
    {id: 4, attr: null} 
]; 

var temp = []; 
for(var i = x.length-1;i>=0;i--){ 
    if (x[i].attr===null) {    //if we have a null 
     temp.unshift(x.splice(i,1)[0]); //remove the element from org and add to temp 
    } 
} 
x = temp.concat(x); //add the original to the temp to maintain the order 
+0

這看起來像迄今爲止最快的實現:http://jsperf.com/js-put-elements-to-array-beginning-on-condition/3 –

0
function customSort(myArray) { 
    var result = []; 
    myArray.map(function(el, idx, arr) { 
    return myArray[idx].attr === null ? result.unshift(myArray[idx]) : result.push(myArray[idx]); 
    }); 
    return result; 
} 
console.log(customSort([ 
    {id: 5, attr: 99}, 
    {id: 7, attr: null}, 
    {id: 2, attr: 8}, 
    {id: 9, attr: 3}, 
    {id: 4, attr: null} 
]));