【问题标题】:How can compare and exclude arrays elements with other arrays elements in react native如何在本机反应中将数组元素与其他数组元素进行比较和排除
【发布时间】:2021-12-15 10:27:11
【问题描述】:

我需要比较两个数组 这是一个数组 [...表演] 这是另一个数组 [...swipeeachotheruserId]

在这个数组中,一些 id 将包含 此 ID 将相同但并非全部相同 [3,5,7,10,14][2,5,7,1,20,14]

有些元素会相同,但并非所有元素都相同

逻辑是

showid===swipeeachotheruserId ?将排除不同的 id 并在此处显示:show id

如何比较和排除这个数组值

【问题讨论】:

  • 预期的输出是什么。

标签: javascript react-native


【解决方案1】:

const showid = [ 3, 5, 7 , 10 ,14 ];
const swipeeachotheruserId = [ 2, 5, 7, 1, 20, 14 ];

const duplicates = showid.filter(value => swipeeachotheruserId.some(oneElement => oneElement === value));

const mergedArray = [ 
  ...showid, 
  ...swipeeachotheruserId.filter(value => !duplicates.some(oneDuplicate => oneDuplicate === value))
];

const arrayWithoutDuplicate = mergedArray.filter(oneElem => !duplicates.some(value => oneElem === value));

console.log(duplicates);
console.log(mergedArray);
console.log(arrayWithoutDuplicate);

【讨论】:

    【解决方案2】:

    如果你想传递两个数组中的对象,使用这个:

    return showid.filter(e=>sipeeachotheruserid.includes(e))
    

    如果你想传递 swipeachotheruserid 中没有的对象,那么使用这个:

    return showid.filter(e=>!swipeeachotheruserid.includes(e))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 2021-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多