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

Int*_*els 0 javascript arrays

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

多维数组,找到项目并移到顶部?

我正在返回一个具有以下内容的对象:

 $.get(uri, function (data) {

    self.options = [];

    $.each(data, function (index, item) {
        self.options.push(item);
    });
 });
Run Code Online (Sandbox Code Playgroud)

self.options []看起来像:

   Object 1: 
          Id: "1"
          Name: "Bill"
   Object 2: 
          Id: "2"
          Name: "Sarah"
   Object 3: 
          Id: "3"
          Name: "Mike"
Run Code Online (Sandbox Code Playgroud)

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

小智 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
)
Run Code Online (Sandbox Code Playgroud)

或者,更紧凑:

array.unshift(array.splice(array.findindex(elt => elt.Name === 'Sarah'), 1)[0])
Run Code Online (Sandbox Code Playgroud)

在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]                             
)
Run Code Online (Sandbox Code Playgroud)

但这并不能解决萨拉失踪的情况,或者萨拉不止一个.更通用的解决方案是根据某些条件将输入数组拆分为两个,然后重新组合它们.这就是这个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);
}
Run Code Online (Sandbox Code Playgroud)

现在,在ES6中,您可以获得结果

tee(a, e => e.Name === 'Sarah')
Run Code Online (Sandbox Code Playgroud)

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

tee(a, function(e) { return e.Name === 'Sarah'; })
Run Code Online (Sandbox Code Playgroud)