首页 > 解决方案 > 基于另一个对象删除数组的项

问题描述

我有一个给定的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]
}

标签: javascriptarrays

解决方案


您可以使用map,reduce和的组合every

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
}


推荐阅读