如何筛选值匹配指定数组元素的对象键值对并按值降序排序
实现方案
核心逻辑
- 第一步:将目标对象转换为
[key, value]格式的可遍历二维数组 - 第二步:过滤出值存在于指定字符串数组中的键值对,可将字符串数组转为
Set提升查找效率 - 第三步:对筛选后的结果按值做降序排序
代码示例(JavaScript)
// 输入示例数据 const sourceObj = { "key1": "stringB", "key2": "stringA", "key3": "stringC", "key4": "stringD" // 不在匹配数组中,会被过滤 }; const matchArr = ["stringA", "stringB", "stringC"]; // 转换为Set,匹配数组元素较多时能大幅提升查找效率 const matchSet = new Set(matchArr); const result = Object.entries(sourceObj) // 筛选值在匹配集合内的键值对 .filter(([_, value]) => matchSet.has(value)) // 按值降序排序,数值类型可直接用 b[1] - a[1] 替换 .sort((a, b) => b[1].localeCompare(a[1])); console.log(result); // 输出示例:[ [ 'key3', 'stringC' ], [ 'key1', 'stringB' ], [ 'key2', 'stringA' ] ]
如果需要最终输出为对象格式,可在排序后追加转换逻辑:
const resultObj = Object.fromEntries(result); console.log(resultObj); // 输出:{ key3: 'stringC', key1: 'stringB', key2: 'stringA' }
其他编程语言适配说明
核心逻辑通用,无需绑定JavaScript:遍历对象所有键值对→保留值在匹配数组中的项→按值做降序排序即可,可根据所用语言的语法调整对应API。
内容的提问来源于stack exchange,提问作者user16780074
相关产品推荐
相关产品推荐

