You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript:如何将数组中identifier为'B'的对象移至末尾?

问题:将指定元素移至数组末尾

现有如下对象数组:

var array = [
    { "identifier": "A" },
    { "identifier": "B" },
    { "identifier": "C" },
    { "identifier": "D" }
]

需要把它处理成这样——所有identifier为"B"的元素移到数组最后:

var array = [
    { "identifier": "A" },
    { "identifier": "C" },
    { "identifier": "D" },
    { "identifier": "B" }
]

用户尝试用map处理,但不知道怎么实现:

array.map((o) => {
  if (o.identifier === 'B') {
     // 此处应如何处理?
  }
 return o;
})

先说明:map做不了这个

map是用来给每个元素做一对一转换的,它返回的数组长度和原数组完全一致,没法调整元素位置或者移动元素,所以用map实现这个需求根本行不通,别在这浪费时间了。

用reduce实现的正确方式

reduce可以灵活构建结果,遍历的时候把非"B"的元素直接放进结果数组,把"B"的元素存起来,最后再追加到末尾:

const processedArray = array.reduce((acc, item) => {
  if (item.identifier === 'B') {
    acc.bElement = item;
  } else {
    acc.result.push(item);
  }
  return acc;
}, { result: [], bElement: null });

// 如果找到B元素,就加到结果最后
if (processedArray.bElement) {
  processedArray.result.push(processedArray.bElement);
}

console.log(processedArray.result);

更简洁的reduce写法

也可以在reduce里维护两个数组,最后合并:

const [nonB, bElements] = array.reduce(([nonB, b], item) => {
  return item.identifier === 'B' 
    ? [nonB, [...b, item]] 
    : [[...nonB, item], b];
}, [[], []]);

const processedArray = nonB.concat(bElements);

补充:不用reduce的更直观写法

如果没硬性要求必须用reduce,直接用filter+concat可读性更高:

const nonBItems = array.filter(item => item.identifier !== 'B');
const bItems = array.filter(item => item.identifier === 'B');
const processedArray = nonBItems.concat(bItems);

这种写法一眼就能看懂,日常开发里更常用。


内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 12:52:42