In theory this sounds reasonably easy, but a certain AI bot keeps giving me incorrect info.
I have data that looks like this:
let newData = {
'2020': { Thing1: ['ABC', '123'], Thing2: ['DEF'] },
'2020.5': { Thing1: ['ABC', '123', 'XYZ'], Thing2: ['DEF'] },
'2020.75': { Thing1: ['ABC', '123'], Thing2: ['XYZ'], Thing3: ['AAA'] }
};
All I want to do is remove values from the “Thing” arrays that are the same across all objects and specific array. In the case above remove ‘ABC’ and ‘123’ from the Thing1 arrays.
The returned data looking like this:
{
'2020': { Thing1: [], Thing2: ['DEF'] },
'2020.5': { Thing1: ['XYZ'], Thing2: ['DEF'] },
'2020.75': { Thing1: [], Thing2: ['XYZ'], Thing3: ['AAA'] }
}
This was the answer I got from the aforementioned AI bot:
const numObjects = Object.keys(newData).length;
_.forEach(newData, (value, key) => {
_.forEach(value, (arr, thing) => {
newData[key][thing] = _.filter(arr, (value) => {
const count = _.countBy(newData, (obj) => obj[thing] && obj[thing].includes(value));
return Object.keys(count).length !== numObjects;
});
});
});
console.log(newData);
But this just returns everything. I don’t think it’s iterating through the actual values in the Thing arrays.
Any help would be most appreciated.
5
Answers
The author’s code mutates the original object.
First we get counts of values, then we clean the arrays.
A pure solution by Damzaky is slower (but could be useful if we need to go pure).
You don’t need the lodash here. The ES6+ allows to do the same things. I’ve added 2 lodash solutions to the benchmark but they are the slowest:
Not sure if this is the most efficient way, but I would get the intersections of every "Thing" first, and then remove them from the "Thing"s:
If you wish to replace the data of
newData
, without a new object, a nestedfor..of Object.keys()
and afilter()
would be enough:Here is a solution using mainly normal JavaScript. I do use
_.uniq
,_.intersection
and_.difference
since they don’t have a simple JavaScipt equivalent.This solution works in a few steps.
_.uniq
"Thing" keys._.intersection
of each "Thing" key._.difference
between the current value and the stored intersection.Note that this answer mutates the original structure.
toRemove
) that contains, for each property, all the values that are common between the original objects.toRemove
counterpart property.