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

Javascript: find match in array of objects and move to first position

本文关键字:移动 位置 第一个 Javascript 对象 数组      更新时间:2023-09-26

我试图实现的与Stackoverflow上另一篇文章中的PHP解决方案类似,但使用了JavaScript:

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

我正在返回一个包含以下内容的对象:

 $.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",并将其上移为数组的第一项。我如何才能做到这一点?*

您可以用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])

findIndex在Internet Explorer中根本不受支持因此要支持IE 11,您可以使用map(自IE 9起)和indexOf(自IE 8起)的组合-这为您提供了完全的、非绿色的跨浏览器兼容性。

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

但这并不能处理莎拉失踪或不止一个莎拉的情况。一个更通用的解决方案是根据某些条件将传入的数组一分为二,然后重新组合。这就是这个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'; })

您可以使用Array.prototype.sort来实现这一点。

例如

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

您可以使用arraysort方法

var array = ['apple','zebra','cherry','grap'];
// 'zebra' at first index of array
array.sort( (first, second) => {
  if(first === 'zebra') return -1;
});
console.log('first', array);
// 'zebra' at last index of array
array.sort( (first, second) => {
  if(second === 'zebra') return -1;
});
console.log('last', array);

这里有一种方法可以满足您的要求。

$.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)
});