JS:在条件开始时将元素放到数组中

时间:2014-03-31 15:30:24

标签: javascript

我有一个像这样的数组:

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

attr === null的所有对象放在数组的开头,而不改变数组中其他元素的顺序,效率最高的是什么? (例如,我需要ID按顺序排列:7,4,5,2,9(7和4的顺序不重要,但5,2,9的顺序绝不能改变。)

简单的小提琴来测试您的代码:http://jsfiddle.net/8GEPC/

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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}]

这是使用reduce的解决方案:

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

答案 2 :(得分: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 array'的前面。

withVal.unshift.apply(withVal, withNull);

Fiddle

答案 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}
]));