I have this array resulting from a function:
final = [
[
[ 0, 'Bowling Ball' ],
[ 0, 'Dirty Sock' ],
[ 0, 'Hair Pin' ],
[ 0, 'Microphone' ]
],
[ 1, 'Hair Pin' ],
[ 1, 'Hair Pin' ],
[ 1, 'Hair Pin' ],
[ 1, 'Half-Eaten Apple' ],
[ 1, 'Half-Eaten Apple' ],
[ 1, 'Half-Eaten Apple' ],
[ 1, 'Half-Eaten Apple' ],
[ 1, 'Bowling Ball' ],
[ 1, 'Bowling Ball' ],
[ 1, 'Bowling Ball' ],
[ 1, 'Toothpaste' ],
[ 1, 'Toothpaste' ],
[ 1, 'Toothpaste' ],
[ 1, 'Toothpaste' ]
]
My ultimate goal is this:
final = [
[ 0, 'Bowling Ball' ],
[ 0, 'Dirty Sock' ],
[ 0, 'Hair Pin' ],
[ 0, 'Microphone' ] ],
[ 1, 'Hair Pin' ],
[ 1, 'Half-Eaten Apple' ],
[ 1, 'Bowling Ball' ],
[ 1, 'Toothpaste' ]
]
That is, I want to remove the repeated nested arrays . This more or less I think I can do but only if I first somehow convert the multidimensional array to a flat one. That is, like this:
final = [
[ 0, 'Bowling Ball' ],
[ 0, 'Dirty Sock' ],
[ 0, 'Hair Pin' ],
[ 0, 'Microphone' ],
[ 1, 'Hair Pin' ],
[ 1, 'Hair Pin' ],
[ 1, 'Hair Pin' ],
[ 1, 'Half-Eaten Apple' ],
[ 1, 'Half-Eaten Apple' ],
[ 1, 'Half-Eaten Apple' ],
[ 1, 'Half-Eaten Apple' ],
[ 1, 'Bowling Ball' ],
[ 1, 'Bowling Ball' ],
[ 1, 'Bowling Ball' ],
[ 1, 'Toothpaste' ],
[ 1, 'Toothpaste' ],
[ 1, 'Toothpaste' ],
[ 1, 'Toothpaste' ]
]
As you can see, a "level" has been removed and now all the "sub.arrays" are on the same level (around the outer array ).
I only find methods to "schedule" the array completely (that is, there is only one array left at the end and everything is together), but not for the latter.
This is what I have tried:
function flattenDeep(final) {
return final.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}
flattenDeep(final);
// final devuelve esto:
final = [0, "Bowling Ball", 0, "Dirty Sock", 0, "Hair Pin", 0, "Microphone", 1, "Hair Pin", 1, "Hair Pin", 1, "Hair Pin", 1, "Half-Eaten Apple", 1, "Half-Eaten Apple", 1, "Half-Eaten Apple", 1, "Half-Eaten Apple", 1, "Bowling Ball", 1, "Bowling Ball", 1, "Bowling Ball", 1, "Toothpaste", 1, "Toothpaste", 1, "Toothpaste", 1, "Toothpaste"]
You can use a special function to flatten your array up to 1 level of sub-arrays.
To achieve this, I am including in my
script
a function that returns the maximum sub-levels of an array, from Kyle Phillips, which I have found in this github repositoryThe problem with your function
flattenDeep
is that it doesn't stop at the level you need, i.e. it converts allArray
and you only need it to convert theArray[Array]
.Solution:
To achieve both, flattening and filtering out duplicates, you could do it like this