I have an array that repeats itself. I'm looking for a way to omit the duplicate values i.e.
[['cream'], ['cake'], ['cheese'], ['bread'], ['cream'], ['cake'], ['cheese'], ['bread'], ['butter']]
becomes
[['cream'], ['cake'], ['cheese'], ['bread'], ['butter']]
any clean way to do this?
CodePudding user response:
console.log(Object.keys([
['cream'],
['cake'],
['cheese'],
['bread'],
['cream'],
['cake'],
['cheese'],
['bread'],
['butter']
].reduce((acc, val) => { // map to object
acc[val] = true
return acc;
}, {})).map(key => [key])) // map object back to array
CodePudding user response:
- Define a
Set
to store array elements - Using
Array#reduce
, iterate over the list. In every iteration, convert the current array to a string by joining its elements usingArray#join
. Then, if the value is not already in the set, add it and push the current array to the accumulated list.
const arr = [['cream'], ['cake'], ['cheese'], ['bread'], ['cream'], ['cake'], ['cheese'], ['bread'], ['butter']];
const set = new Set();
const res = arr.reduce((list, e) => {
const val = e.join();
if(!set.has(val)) {
set.add(val);
list.push(e);
}
return list;
}, []);
console.log(res);
CodePudding user response:
One liner here:
const data = [['cream'], ['cake'], ['cheese'], ['bread'], ['cream'], ['cake'], ['cheese'], ['bread'], ['butter']];
console.log([...new Set(data.flat())].map(i => [i]))