[英]JavaScript move array element to end of array
編輯-2種優雅的解決方案
兩種優雅的解決方案,分別來自Pranav和Bekim。 謝謝,測試和工作都完美。
一
for(var x in data)data[x].name == "other" ? data.push( data.splice(x,1)[0] ) : 0;
二
var res = data.slice(),
len = res.length;
for (var i = 0; i < len; i++) {
if (res[i].name == 'other') {
res.push(res.splice(i, 1)[0]);
i--;
len--;
}
}
使用JS工具
角1.5.6,lodash 4.1x
在這種情況下,我有一個按字母順序排序的對象數組,例如,下面的sortedData等。但是,在該數組中還包含了所有Other
,這顯然也按字母順序排序。 我想從數組中刪除其他數組,然后移到數組末尾而不弄亂當前已排序的數組。
注意
我目前的下面方法行得通,但很難看。 JS,angular或lodash的功能是否更優雅?
var data = [
{id:1,name:'apple'},
{id:2,name:'banana'},
{id:3,name:'other'},
{id:4,name:'tomato'},
{id:5,name:'strawberry'}
];
function move(array, fromIndex, toIndex) {
array.splice(toIndex, 1, array.splice(fromIndex, 1)[0]);
return array;
}
var moved = move(
data,
_.findIndex(data, ['name', 'other']),
Object.keys(data).length
);
理想結果
var data = [
{id:1,name:'one'},
{id:2,name:'two'},
{id:4,name:'four'},
{id:5,name:'five'}
{id:3,name:'other'},
]
您可以使用純Javascript(ES6)執行Array.findIndex,而無需使用任何庫:
data.push(data.splice(data.findIndex(v => v.name == 'other'), 1)[0])
Array.findIndex是新的 ,但如今人們實際使用的大多數瀏覽器都具有它。 因此,您可能可以使用它。 (Edge支持它,但不支持IE)。
如果您發現[0]
丑陋,則可以使用spread展開數組的包裝(這樣,它也可以通過一項更改而適用於多個項目):
data.push(...data.splice(data.findIndex(v => v.name == 'other'), 1))
一個普通的(Vanilla)JavaScript可以正常工作:
for(var x in data)data[x].name == "other" ? data.push( data.splice(x,1)[0] ) : 0;
var data = [ {id:1,name:'apple'}, {id:2,name:'banana'}, {id:3,name:'other'}, {id:4,name:'tomato'}, {id:5,name:'strawberry'} ]; for(var x in data)data[x].name == "other" ? data.push( data.splice(x,1)[0] ) : 0; console.log( JSON.stringify(data))
使用簡單的for循環
var data = [{ id: 1, name: 'apple' }, { id: 2, name: 'banana' }, { id: 3, name: 'other' }, { id: 4, name: 'tomato' }, { id: 5, name: 'strawberry' }]; // store the length of array var len = data.length; // iterate over all array elements for (var i = 0; i < len; i++) { // check value is `other` if (data[i].name == 'other') { // if value is other then move the object data.push(data.splice(i, 1)[0]); // decrement i since the element removed i--; // decrement len to avoid moved element len--; } } console.log(data);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.