Javascript:在对象数组中找到匹配并移动到第一个位置

时间:2016-03-24 01:03:53

标签: javascript arrays

我试图完成的内容类似于Stackoverflow上其他帖子的PHP解决方案,但是使用JavaScript:

Multidimensional array, find item and move to the top?

我正在使用以下内容返回一个对象:

 $.get(uri, function (data) {

    self.options = [];

    $.each(data, function (index, item) {
        self.options.push(item);
    });
 });

self.options []看起来像:

   Object 1: 
          Id: "1"
          Name: "Bill"
   Object 2: 
          Id: "2"
          Name: "Sarah"
   Object 3: 
          Id: "3"
          Name: "Mike"

我需要找到" Sarah"在数组对象中并将其移动到数组的第一项。我怎样才能做到这一点?*

4 个答案:

答案 0 :(得分:10)

您可以在JavaScript中直接写出问题的英文描述。

array.unshift(                      // add to the front of the array
  array.splice(                     // the result of deleting items
    array.findIndex(                // starting with the index where
      elt => elt.Name === 'Sarah'), // the name is Sarah
  1)[0]                             // and continuing for one item
)

或者,更紧凑:

array.unshift(array.splice(array.findindex(elt => elt.Name === 'Sarah'), 1)[0])
完全不支持Internet Explorer中的

findIndex 因此,为了支持IE 11,您可以使用map(自IE 9)和indexOf的组合(因为IE 8) ) - 这为您提供完整的,非绿色的,跨浏览器的兼容性。

array.unshift(                      
  array.splice(                     
    array.map(function(e){ return e.Name}).indexOf('Sarah'), 
  1)[0]                             
)

但是,这并没有处理Sarah失踪的情况,或者Sarah不止一个。更通用的解决方案是根据某些条件将输入数组拆分为两个,然后重新组合它们。这是tee函数的作用:

function tee(a, fn) {
  var non_matches = [];
  var matches = a.filter(function(e, i, a) {
    var match = fn(e, i, a);
    if (!match) non_matches.push(e);
    return match;
  });
  return matches.concat(non_matches);
}

现在,在ES6中,您可以使用

获取结果
tee(a, e => e.Name === 'Sarah')

对于旧版浏览器,使用ES5:

tee(a, function(e) { return e.Name === 'Sarah'; })

答案 1 :(得分:2)

您可以使用Array.prototype.sort来完成此任务。

E.g。

var arr = [];
arr.push({Id:"1", Name:"Bill"});
arr.push({Id:"2", Name:"Sarah"});
arr.push({Id:"3", Name:"Mike"});

arr.sort(function(first, second) {
  if (second.Name == "Sarah") return 1;
});

console.log(arr);
// [Object { Id="2",  Name="Sarah"}, Object { Id="1",  Name="Bill"}, Object { Id="3",  Name="Mike"}]

或另一种选择,

var arr = [];
arr.push({Id:"1", Name:"Bill"});
arr.push({Id:"3", Name:"Mike"});
arr.push({Id:"2", Name:"Sarah"});

function getIndexByName(name) {
    for(var i = 0; i < arr.length; i++) {
        if (arr[i].Name == name) {
            return i;
        }
    }
}

var pos = getIndexByName("Sarah");
arr.splice(0, 0, arr[pos++]) // Insert Sarah at `arr` first position
arr.splice(pos, 1); // Remove old Sarah

答案 2 :(得分:0)

您可以使用sort数组方法

var a = ['a','b','c','d'];

// 'b' at first index
a.sort( (f,s) => {
  if(f === 'b') return -1;
});
console.log('first', a);

// 'b' at last index
a.sort( (f,s) => {
  if(s === 'b') return -1;
});
console.log('last', a);

答案 3 :(得分:-1)

这是一种做你要求的方法。

$.get(uri, function (data) {

   self.options = [];
   var chosenName = 'Sarah'
   var tmp = [];
   $.each(data, function (index, item) {
       // if we find it while iterating through do not add it, store it it tmp
       if (item.Name === chosenName) {
          tmp.push(item);
       } else {
          self.options.push(item);
       }
   });
   // if we found it push it to the front of the array
   if (tmp.length > 0) self.options = tmp.concat(self.options)
});