Javascript 重新排序数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2440700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:21:22  来源:igfitidea点击:

Reordering arrays

javascriptarrayssorting

提问by Wurlitzer

Say, I have an array that looks like this:

说,我有一个看起来像这样的数组:

var playlist = [
    {artist:"Herbie Hancock", title:"Thrust"},
    {artist:"Lalo Schifrin", title:"Shifting Gears"},
    {artist:"Faze-O", title:"Riding High"}
];

How can I move an element to another position?

如何将元素移动到另一个位置?

I want to move for example, {artist:"Lalo Schifrin", title:"Shifting Gears"}to the end.

例如,我想移动{artist:"Lalo Schifrin", title:"Shifting Gears"}到最后。

I tried using splice, like this:

我尝试使用 splice,如下所示:

var tmp = playlist.splice(2,1);
playlist.splice(2,0,tmp);

But it doesn't work.

但它不起作用。

回答by Matt

The syntax of Array.spliceis:

的语法Array.splice是:

yourArray.splice(index, howmany, element1, /*.....,*/ elementX);

Where:

在哪里:

  • indexis the position in the array you want to start removing elements from
  • howmanyis how many elements you want to remove from index
  • element1, ..., elementXare elements you want inserted from position index.
  • index是您要开始从中删除元素的数组中的位置
  • howmany是您要从索引中删除的元素数量
  • element1, ..., elementX是您要从位置index插入的元素。

This means that splice()can be used to remove elements, add elements, or replace elements in an array, depending on the arguments you pass.

这意味着splice()可用于删除元素、添加元素或替换数组中的元素,具体取决于您传递的参数。

Note that it returns an array of the removed elements.

请注意,它返回一个已删除元素的数组。

Something nice and generic would be:

好的和通用的东西是:

Array.prototype.move = function (from, to) {
  this.splice(to, 0, this.splice(from, 1)[0]);
};

Then just use:

然后只需使用:

var ar = [1,2,3,4,5];
ar.move(0,3);
alert(ar) // 2,3,4,1,5

Diagram:

图表:

Algorithm diagram

算法图

回答by CMS

If you know the indexes you could easily swap the elements, with a simple function like this:

如果您知道索引,则可以使用如下简单的函数轻松交换元素:

function swapElement(array, indexA, indexB) {
  var tmp = array[indexA];
  array[indexA] = array[indexB];
  array[indexB] = tmp;
}

swapElement(playlist, 1, 2);
// [{"artist":"Herbie Hancock","title":"Thrust"},
//  {"artist":"Faze-O","title":"Riding High"},
//  {"artist":"Lalo Schifrin","title":"Shifting Gears"}]

Array indexes are just properties of the array object, so you can swap its values.

数组索引只是数组对象的属性,因此您可以交换其值。

回答by chmanie

Here is an immutable version for those who are interested:

对于感兴趣的人,这是一个不可变的版本:

function immutableMove(arr, from, to) {
  return arr.reduce((prev, current, idx, self) => {
    if (from === to) {
      prev.push(current);
    }
    if (idx === from) {
      return prev;
    }
    if (from < to) {
      prev.push(current);
    }
    if (idx === to) {
      prev.push(self[from]);
    }
    if (from > to) {
      prev.push(current);
    }
    return prev;
  }, []);
}

回答by Trevor

Change 2 to 1 as the first parameter in the splice call when removing the element:

删除元素时,将 2 更改为 1 作为 splice 调用中的第一个参数:

var tmp = playlist.splice(1, 1);
playlist.splice(2, 0, tmp[0]);

回答by arthurDent

With ES6you can do something like this:

使用ES6,您可以执行以下操作:

const swapPositions = (array, a ,b) => {
  [array[a], array[b]] = [array[b], array[a]]
}

let array = [1,2,3,4,5];
swapPositions(array,0,1);

/// => [2, 1, 3, 4, 5]

回答by Andy E

You could always use the sort method, if you don't know where the record is at present:

如果您不知道当前记录在哪里,您总是可以使用 sort 方法:

playlist.sort(function (a, b) {
    return a.artist == "Lalo Schifrin" 
               ? 1    // Move it down the list
               : 0;   // Keep it the same
});

回答by Jaacko Torus

EDIT: Please check out Andy's answeras his answer came first and this is solely an extension of his

编辑:请查看安迪的回答,因为他的回答是第一位的,这只是他的延伸

I know this is an old question, but I think it's worth it to include Array.prototype.sort().

我知道这是一个老问题,但我认为值得将Array.prototype.sort().

Here's an example from MDN along with the link

这是来自 MDN 的示例以及链接

var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers);

// [1, 2, 3, 4, 5]

Luckily it doesn't only work with numbers:

幸运的是,它不仅适用于数字:

arr.sort([compareFunction])

compareFunction

Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.

arr.sort([compareFunction])

compareFunction

指定定义排序顺序的函数。如果省略,则根据每个字符的 Unicode 代码点值,根据每个元素的字符串转换,对数组进行排序。

I noticed that you're ordering them by first name:

我注意到你是按名字来排序的:

let playlist = [
    {artist:"Herbie Hancock", title:"Thrust"},
    {artist:"Lalo Schifrin", title:"Shifting Gears"},
    {artist:"Faze-O", title:"Riding High"}
];

// sort by name
playlist.sort((a, b) => {
  if(a.artist < b.artist) { return -1; }
  if(a.artist > b.artist) { return  1; }

  // else names must be equal
  return 0;
});

note that if you wanted to order them by last name you would have to either have a key for both first_name& last_nameor do some regex magic, which I can't do XD

请注意,如果您想按姓氏订购它们,则必须同时拥有first_name&的密钥,last_name或者执行一些正则表达式魔术,我不能这样做 XD

Hope that helps :)

希望有帮助:)

回答by JamieJag

Try this:

尝试这个:

playlist = playlist.concat(playlist.splice(1, 1));

回答by Okonomiyaki3000

If you only ever want to move one item from an arbitrary position to the end of the array, this should work:

如果您只想将一项从任意位置移动到数组的末尾,这应该有效:

function toEnd(list, position) {
    list.push(list.splice(position, 1));
    return list;
}

If you want to move multiple items from some arbitrary position to the end, you can do:

如果要将多个项目从某个任意位置移动到末尾,可以执行以下操作:

function toEnd(list, from, count) {
    list.push.apply(list, list.splice(from, count));
    return list;
}

If you want to move multiple items from some arbitrary position to some arbitrary position, try:

如果要将多个项目从某个任意位置移动到某个任意位置,请尝试:

function move(list, from, count, to) {
    var args = [from > to ? to : to - count, 0];
    args.push.apply(args, list.splice(from, count));
    list.splice.apply(list, args);

    return list;
}

回答by David

As a simple mutable solution you can call splice twice in a row:

作为一个简单的可变解决方案,您可以连续调用 splice 两次:

playlist.splice(playlist.length - 1, 1, ...playlist.splice(INDEX_TO_MOVE, 1))

On the other hand, a simple inmutable solution could use slice since this method returns a copy of a section from the original array without changing it:

另一方面,一个简单的不可变解决方案可以使用 slice,因为此方法返回原始数组中某个部分的副本,而不对其进行更改:

const copy = [...playlist.slice(0, INDEX_TO_MOVE - 1), ...playlist.slice(INDEX_TO_MOVE), ...playlist.slice(INDEX_TO_MOVE - 1, INDEX_TO_MOVE)]