How can I deconstruct an array, and put it into the array which it is getting mapped on, and then continue sorting on that?
The array looks like the following after filtering it:
[
['traitName', 'value'],
['traitName', ['value01', 'value02', 'value03' ...] ],
//...
]
I want to check every trait, and check if the first index is an array, then deconstruct that, and put it into this array like this:
[
['traitName', 'value'],
['traitName', value01],
['traitName', value02],
['traitName', value03],
//...
],
Then I can continue sorting on this array.
Object.entries(nft)
.filter((val: any) => val[0] !== 'Attributes' && data.attributes[val[0]] !== undefined)
.sort((a: any, b: any) => {
if (typeof a[1] === 'number') return Infinity;
return (
data.attributes[a[0]]?.values[a[1]]?.distribution - data.attributes[b[0]]?.values[b[1]]?.distribution
);
})
I need to this between the filter and sorting I think.
This may be achieved by using .map, .concat and .flat(), in one line as shown below:
arr.map(([x, y]) => ([].concat(y).map(z => ([x, z])))).flat()
One possible solution is shown below:
Code Snippet
const arr = [
['traitName', 'value'],
['traitName', ['value01', 'value02', 'value03'] ]
];
const res = arr.map(
ar => (
[].concat(ar[1])
.map(x => ([ar[0], x]))
)
)
.flat();
console.log('result using .map & .flat: ', res);
// or in just one line:
console.log(
'one line result: ',
arr.map(([x, y]) => ([].concat(y).map(z => ([x, z])))).flat()
);
Explanation
[].concat() to treat the second element of each inner-array as an array.map() to iterate over the inner-array element/s.flat() to flatten the resulting array.you can use this,
const a = [
['traitName', 'value'],
['traitName', ['value01', 'value02', 'value03'] ]
]
let final = []
a.forEach((item)=>{
console.log(typeof item[1])
if(typeof item[1] == "string") {
final.push(item)
} else if(typeof item[1] == 'object') {
let len = item[1].length
item[1].forEach((item2) =>{
let e = [item[0], item2]
final.push(e)
})
}
})
console.log(final)