将数组中的特定值对象移到末尾 [英] Move a particular value object in array to end

查看:182
本文介绍了将数组中的特定值对象移到末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种将对象移动到数组末尾的方法

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 than b and a will be move to a higher index than b
  • 0: means a is equal to b and no change will be made.
  • -1: means a is less than b and a will be move to a lower index than b.

有关更多信息,请参阅: 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆