首页 > 解决方案 > 比较对象数组并返回不在其中一个数组中的新对象数组

问题描述

我一直无法弄清楚如何让它发挥作用。

基本上,我有两个数组。这些数组将包含对象。

第一个数组是包含用户喜爱电台的对象数组。

第二个数组是包含需要移除的站点的对象数组。

我想比较第一个和第二个数组,并返回一个新数组,其中包含不在删除站数组中的站...

例如...

const favourites = [{ station_name: 'Kyle of Lochalsh', crs_code: 'KYL' }, { station_name: 'Connel Ferry', crs_code: 'CON' }, { station_name: 'Oban', crs_code: 'OBN' }]

const toBeRemoved = [{ station_name: 'Kyle of Lochalsh', crs_code: 'KYL' }]

然后,我希望返回一个包含其他 2 个站点的数组...

我花了几个小时试图弄清楚如何做到这一点,但似乎不起作用!

TIA

标签: javascriptarrays

解决方案


以下代码演示了具有相同属性的两个对象可能不相等:

const ob_1={color:'black', size:'big'},  
      ob_2={color:'black', size:'big'};  
console.log(ob_1==ob_2); // false  

所以我们需要经常进行深度比较:

const favourites = [
  { station_name: 'Kyle of Lochalsh', crs_code: 'KYL' },
  { station_name: 'Connel Ferry', crs_code: 'CON' },
  { station_name: 'Oban', crs_code: 'OBN' }
];
const toBeRemoved = [
  { station_name: 'Kyle of Lochalsh', crs_code: 'KYL' }
];

console.log(

  // Array.filter applies our custom function to each item in the 
  // `favourites` array and returns a new (smaller) array containing
  // all items for which our custom function returns true
  favourites.filter(

    // Our custom function (using "arrow function" syntax) takes
    // a station object and uses `Array.some` to compare it to each 
    // item in the `toBeRemoved` array. Our custom function returns
    // true if the current station is not in `toBeRemoved`.
    (station) =>

      // Array.some takes another custom function which is applied
      // to each item in `toBeRemoved`, returning true if this 
      // custom function returns true for at least one item

      !toBeRemoved.some(
        // This custom function takes a station object (called `st`)
        // and "deeply" compares each property against the same 
        // property in the current station of the `favorites` 
        // array, returning true if both properties match

        (st) =>
          st.station_name == station.station_name &&
          st.crs_code == station.crs_code
      )
  )
);


推荐阅读