Wur*_*zer 89 javascript arrays sorting
说,我有一个看起来像这样的数组:
var playlist = [
{artist:"Herbie Hancock", title:"Thrust"},
{artist:"Lalo Schifrin", title:"Shifting Gears"},
{artist:"Faze-O", title:"Riding High"}
];
Run Code Online (Sandbox Code Playgroud)
如何将元素移动到另一个位置?
我想举例,{artist:"Lalo Schifrin", title:"Shifting Gears"}到最后.
我尝试使用splice,如下所示:
var tmp = playlist.splice(2,1);
playlist.splice(2,0,tmp);
Run Code Online (Sandbox Code Playgroud)
但它不起作用.
Mat*_*att 204
语法Array.splice是:
yourArray.splice(index, howmany, element1, /*.....,*/ elementX);
Run Code Online (Sandbox Code Playgroud)
哪里:
这意味着splice()可以使用它来删除元素,添加元素或替换数组中的元素,具体取决于您传递的参数.
请注意,它返回已删除元素的数组.
好的和通用的东西是:
Array.prototype.move = function (from, to) {
this.splice(to, 0, this.splice(from, 1)[0]);
};
Run Code Online (Sandbox Code Playgroud)
然后使用:
var ar = [1,2,3,4,5];
ar.move(0,3);
alert(ar) // 2,3,4,1,5
Run Code Online (Sandbox Code Playgroud)
图:
CMS*_*CMS 19
如果你知道索引,你可以轻松地交换元素,使用这样一个简单的函数:
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"}]
Run Code Online (Sandbox Code Playgroud)
数组索引只是数组对象的属性,因此您可以交换其值.
chm*_*nie 10
对于那些感兴趣的人,这是一个不可变的版本:
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;
}, []);
}
Run Code Online (Sandbox Code Playgroud)
使用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]
Run Code Online (Sandbox Code Playgroud)
不可变版本,无副作用(n\xe2\x80\x99t 会改变原始数组):
\nconst testArr = [1, 2, 3, 4, 5];\n\nfunction move(from, to, arr) {\n const newArr = [...arr];\n\n const item = newArr.splice(from, 1)[0];\n newArr.splice(to, 0, item);\n\n return newArr;\n}\n\nconsole.log(move(3, 1, testArr));\n\n// [1, 4, 2, 3, 5]\nRun Code Online (Sandbox Code Playgroud)\n代码笔: https: //codepen.io/mliq/pen/KKNyJZr
\n如果您不知道当前记录在哪里,您总是可以使用 sort 方法:
playlist.sort(function (a, b) {
return a.artist == "Lalo Schifrin"
? 1 // Move it down the list
: 0; // Keep it the same
});
Run Code Online (Sandbox Code Playgroud)
删除元素时,将2更改为1作为splice调用中的第一个参数:
var tmp = playlist.splice(1, 1);
playlist.splice(2, 0, tmp[0]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
76966 次 |
| 最近记录: |