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

使用Lodash对比数组并按指定数组排序目标变量

用Lodash实现按arr2顺序排序destination变量

这问题我熟,用Lodash的话其实两步就能搞定——先建立arr2元素的顺序映射,再基于这个映射对destination排序就行。我给你拆解下具体操作:

第一步:创建arr2的顺序映射表

我们需要先把arr2里每个元素的file字段(因为你提到source是依据arr1和source的file字段关联的)和它在arr2中的位置索引对应起来,这样后续排序时能快速找到每个元素的目标位置。

用Lodash的_.reduce就能轻松生成这个映射:

// 生成file字段到arr2中索引的映射
const arr2OrderMap = _.reduce(arr2, (acc, item, index) => {
  acc[item.file] = index;
  return acc;
}, {});

第二步:按映射表排序destination

有了顺序映射后,用Lodash的_.sortBy方法,根据destination每个元素的file字段去映射表里找对应的索引,以此作为排序依据即可:

// 按arr2的顺序排序destination
const sortedDestination = _.sortBy(destination, item => arr2OrderMap[item.file]);

完整示例

给你个完整的代码示例,方便你对照理解:

// 模拟你的数据结构
const arr1 = [
  { src: 'banner', file: 'home-banner.jpg' },
  { src: 'hero', file: 'home-hero.jpg' },
  { src: 'footer', file: 'home-footer.jpg' }
];

const arr2 = [
  { src: 'hero', file: 'home-hero.jpg' },
  { src: 'footer', file: 'home-footer.jpg' },
  { src: 'banner', file: 'home-banner.jpg' }
];

const destination = [
  { file: 'home-banner.jpg', url: '/assets/banner.jpg' },
  { file: 'home-hero.jpg', url: '/assets/hero.jpg' },
  { file: 'home-footer.jpg', url: '/assets/footer.jpg' }
];

// 生成顺序映射
const arr2OrderMap = _.reduce(arr2, (acc, item, index) => {
  acc[item.file] = index;
  return acc;
}, {});

// 排序后的结果
const sortedDestination = _.sortBy(destination, item => arr2OrderMap[item.file]);

console.log(sortedDestination);
// 输出顺序会和arr2一致:hero → footer → banner

补充说明

  • 如果你的arr2和destination的关联字段不是file,只需要把代码里的item.file替换成对应的关联字段就行(比如你提到的src键,根据实际关联逻辑调整)。
  • 如果destination里存在arr2中没有的元素,这些元素会被排到最后(因为arr2OrderMap[item.file]会是undefined,_.sortBy会把undefined值的元素放在末尾)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:23:13