As the title suggests, I am trying to create a single array of strings:
['string1', 'string2', 'string3']
Out of an array of objects with arrays of strings within those objects:
[
{
array_of_strings: ['string1', 'string2', 'string3']
},
{
array_of_strings: ['string1', 'string4', 'string5']
},
{
array_of_strings: ['string6', 'string3', 'string2']
}
]
As you can see there is a possibility that the nested arrays may contain the same strings as each other, and I am trying to de-duplicate at the same time. I got very lost in map
, filter
and reduce
. But nothing really outputs the data as needed.
Any guidance would be appreciated.
CodePudding user response:
You can use a javascript Set
for this, check the docs
const array = [
{
array_of_strings: ["string1", "string2", "string3"],
},
{
array_of_strings: ["string1", "string4", "string5"],
},
{
array_of_strings: ["string6", "string3", "string2"],
},
];
const result = array.reduce((acc, { array_of_strings }) => {
return acc.concat(array_of_strings);
}, []);
const unique = new Set(result);
const uniqueArray = Array.from(unique);
console.log(uniqueArray);
CodePudding user response:
First you want to "regroup" all of thoses strings together in the same array :
const fullDatas = [
{
array_of_strings: ["string1", "string2", "string3"],
},
{
array_of_strings: ["string1", "string4", "string5"],
},
{
array_of_strings: ["string6", "string3", "string2"],
},
];
const allStrings = fullDatas.reduce((acc, currentValue)) => {
return acc.concat(currentValue.array_of_strings);
}, []);
then you can have a look at this thread
and use it :
const uniq = [...new Set(allStrings)];
CodePudding user response:
You need none of map
/filter
/reduce
:-) Use flatMap
, then deduplicate:
const data = [
{
array_of_strings: ['string1', 'string2', 'string3']
},
{
array_of_strings: ['string1', 'string4', 'string5']
},
{
array_of_strings: ['string6', 'string3', 'string2']
}
];
const result = Array.from(new Set(data.flatMap(o => o.array_of_strings)));
console.log(result);
CodePudding user response:
If I understand your question correctly(to get all the elements appear more than once),we can use Array.filter()
,Array.reduce()
, Array.map()
to do it
let data = [
{
array_of_strings: ['string1', 'string2', 'string3']
},
{
array_of_strings: ['string1', 'string4', 'string5']
},
{
array_of_strings: ['string6', 'string3', 'string2']
}
]
data = data.map(d => d.array_of_strings).flat().reduce((a,v) =>{
a[v] = a[v]??0
a[v] = 1
return a
},{})
let result = Object.entries(data).filter(i => i[1] > 1).map(i => i[0])
console.log(result)