javascript - 基于另一个对象删除数组的项
问题描述
我有一个给定的checkIDs
数组引用phrases
对象的 id。
我想checkIDs
使用函数修改并返回一个新数组,removeSameTranslates
以便里面只有checkIDs
具有唯一翻译的 id。
让我们用短语对象说我们有 1 和 5 具有完全相同的翻译。如果我们有,const checkIDs = [1,5];
那么我们应该只保留第一个并[1]
作为最终结果返回。因为 1 和 5 的翻译是equel。
const phrases = {
1: {ref: 'some English text', translate: 'some translation1'},
2: {ref: 'some English text2', translate: 'some translation2'},
3: {ref: 'some English text3', translate: 'some translation8'},
4: {ref: 'some English text4', translate: 'some translation3'},
5: {ref: 'some English text4', translate: 'some translation1'},
}
// 1 and 5 both point to a phrase with same translate so we should only keep one
const checkIDs = [1,2,3,5];
const newIDs = removeSameTranslates(checkIDs);
console.log(newIDs);
// remove one of the ids with equel translations and return new array of ids
function removeSameTranslates(checkIDs) {
// should return [1,2,3]
}
解决方案
const phrases = {
1: {ref: 'some English text', translate: 'some translation1'},
2: {ref: 'some English text2', translate: 'some translation2'},
3: {ref: 'some English text3', translate: 'some translation8'},
4: {ref: 'some English text4', translate: 'some translation3'},
5: {ref: 'some English text4', translate: 'some translation1'},
};
const checkIDs = [1,2,3,5];
const newIDs = removeSameTranslates(checkIDs);
console.log(newIDs);
function removeSameTranslates(checkIDs) {
return checkIDs
.map(id => ({id, ...phrases[id]})) // Convert the IDs to Objects
.reduce(
(res, phrase) => {
if (res.every(p => p.translate !== phrase.translate)) { // Check translation
res.push(phrase);
}
return res;
},
[]
)
.map(({id}) => id); // Convert the Objects back to IDs
}
推荐阅读
- java - 如何在android中的活动之间使用EventBus
- python - python“==”如何比较两个标识符
- facebook-graph-api - 将facebook页面订阅到应用程序时如何解决“需要参数subscribed_fields”错误?
- python - 键盘事件未使用 pywin32 发送到窗口
- timezone - Eiffel:我如何处理时区?
- oracle - Oracle - 从主表及其历史表中的客户记录中选择
- mongodb - MongoDB v4.0.0 副本配置设置失败
- python - SQLalchemy query().filter_by(invalid_id).first() 抛出错误而不是 None
- php - 如何通过基于 2 个属性值的组合逻辑对对象数组进行排序?
- html - 选择 CSS 中没有 HTML 标签/元素