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

Ruby按自定义类型优先级从对象数组返回指定对象

按优先级从对象数组中匹配指定type的对象

问题场景

现有一个对象数组,需根据type字段按以下优先级返回特定对象:

  • 优先查找type为video的对象,存在则直接返回
  • 若不存在video类型,查找type为file的对象,存在则返回
  • 若前两者都不存在,返回type为audio的对象

示例数组:

const a = [
  { id: 1, type: 'video', format: 'mp4' },
  { id: 2, type: 'audio', format: 'mp3' },
  { id: 3, type: 'file', format: 'txt' },
  { id: 4, type: 'exe', format: 'exe' }
];

示例结果:

  • 原数组中存在video类型,返回索引0的对象
  • 若移除video类型对象,返回file类型的对象(原数组索引2)
  • 若video和file都不存在,返回audio类型对象

解决方案

利用数组的find()方法按优先级顺序依次查找即可。find()会返回第一个满足条件的元素,正好匹配需求中的优先级规则。

代码实现

function getPriorityItem(arr) {
  return arr.find(item => item.type === 'video') ||
         arr.find(item => item.type === 'file') ||
         arr.find(item => item.type === 'audio');
}

// 测试用例
const originalArr = [
  { id: 1, type: 'video', format: 'mp4' },
  { id: 2, type: 'audio', format: 'mp3' },
  { id: 3, type: 'file', format: 'txt' },
  { id: 4, type: 'exe', format: 'exe' }
];

// 原数组测试
console.log(getPriorityItem(originalArr)); 
// 输出: { id: 1, type: 'video', format: 'mp4' }

// 无video类型的数组测试
const noVideoArr = originalArr.filter(item => item.type !== 'video');
console.log(getPriorityItem(noVideoArr)); 
// 输出: { id: 3, type: 'file', format: 'txt' }

// 无video和file类型的数组测试
const onlyAudioArr = originalArr.filter(item => !['video', 'file'].includes(item.type));
console.log(getPriorityItem(onlyAudioArr)); 
// 输出: { id: 2, type: 'audio', format: 'mp3' }

补充说明

如果需要处理数组中连audio类型都不存在的情况,可以在最后添加默认值,比如:

return arr.find(item => item.type === 'video') ||
       arr.find(item => item.type === 'file') ||
       arr.find(item => item.type === 'audio') || null;

这样当三种类型都不存在时,会返回null,可根据实际业务需求调整默认值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 23:45:43