将数组中的特定值对象移到末尾 [英] Move a particular value object in array to end
问题描述
我正在尝试找到一种将对象移动到数组末尾的方法
I'm trying to find a way to move an object to the end of the array
我有这个对象数组:
[
{"id":"4","name":"Boaz"},
{"id":"2","name":"Shareen"},
{"id":"3","name":"Simon"},
{"id":"1","name":"Miriam"}
]
我想将整个 {"id":"3","name":"Simon"} 移到所有内容的末尾.对于此处,我有解决方案.但是我的问题是,每次特定对象不在第二位置时,都有一种方法可以检查id=3
的对象并将其移动到使用underscoreJS
I want to move the whole set {"id":"3","name":"Simon"} to the end of it all. I have solution for this here. But my problem is every time that particular object is not coming in second position is there a way to check the object of id=3
and shift that to end using underscoreJS
推荐答案
您可以对数组进行排序.
You can just sort array.
Array.sort 期望有3种可能值作为返回值.
Array.sort expects 3 possible values as return value.
- 1:表示
a
大于b
,并且a
将移至比b
高的索引
- 0:表示
a
等于b
,并且不会进行任何更改. - -1:表示
a
小于b
,并且a
将移动到比b
更低的索引.
- 1: means
a
is greater thanb
anda
will be move to a higher index thanb
- 0: means
a
is equal tob
and no change will be made. - -1: means
a
is less thanb
anda
will be move to a lower index thanb
.
有关更多信息,请参阅: Javascript的sort()如何工作?
For more information please refer: How does Javascript's sort() work?
var data = [
{"id":"4","name":"Boaz"},
{"id":"2","name":"Shareen"},
{"id":"3","name":"Simon"},
{"id":"1","name":"Miriam"}
]
data.sort(function(a,b){
return a.id == 3 ? 1 : 0
})
console.log(data)
另一种方法可以过滤出具有必要ID的对象,将它们从当前位置移除并将其推回去,但这在我看来是太多的工作了.排序是上下移动对象的理想方法.
An alternate method could to filter out objects with necessary id, remove them from current position and the push them back, but this is too much work in my understanding. Sort is ideal way to move object up or down the order.
这篇关于将数组中的特定值对象移到末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!