![](/img/trans.png)
[英]Compare Two Arrays Of Objects and return a new array if value is true in Javascript
[英]Compare arrays of objects and return new array of objects that are not in one of the arrays
我一直无法弄清楚如何让它发挥作用。
基本上,我有两个 arrays。 这些 arrays 将包含对象。
第一个数组是包含用户喜爱电台的对象数组。
第二个数组是包含需要移除的站点的对象数组。
我想比较第一个和第二个数组,并返回一个新数组,其中包含不在删除站数组中的站...
例如...
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
以下代码演示了两个具有相同属性的 object 可能被认为不相等:
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 ) ) );
您只需要像这样根据第二个过滤第一个 - :
const favouriteArrayMap = favourites.reduce((acc, item) => ({...acc, [item.crs_code]: 1}), {});
const finalArr = favourites.filter(item => !favouriteArrayMap[item.crs_code]);
这是比使用.includes
或.some
更优化的解决方案,并且将以线性复杂度运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.