Skip to content

Instantly share code, notes, and snippets.

@psenger
Last active July 5, 2023 14:06
Show Gist options
  • Select an option

  • Save psenger/b0b86b5b42627d4d69a54a140507c5c7 to your computer and use it in GitHub Desktop.

Select an option

Save psenger/b0b86b5b42627d4d69a54a140507c5c7 to your computer and use it in GitHub Desktop.
[An array of data, that has an array of sub data] #JavaScript #Array #flatMap #flat #reduce #reduceRIght
/**
* Problem: an array of data, that has an array of sub data.
* Three ways to do this:
* - map+split, reduce, push+spread, sort ( side effect: order is not retained )
* - map+split, flat
* - flatMap+split
*/
const values = 'a|b|c|d,e|f,g|h|i|j|k|l'
const A = values.split(',').map((v)=>v.split('|')).reduce((acc,v)=>{
v.push(...acc)
return v
}, [])
A.sort() //<<< need to sort, because it is mixed up
console.log(JSON.stringify(A, null, 4));
const B = values.split(',').map((v)=>v.split('|')).flat()
console.log(JSON.stringify(B, null, 4));
const C = values.split(',').flatMap((v)=>v.split('|'))
console.log(JSON.stringify(C, null, 4));
// starts at the end, and works backwards
const rr = [1,2,3,4,5].reduceRight((acc,v)=>{
console.log(acc,v);
return v
}, 0)
// 0 5
// 5 4
// 4 3
// 3 2
// 2 1
// starts at the beginning, and works forwards
const rl = [1,2,3,4,5].reduce((acc,v)=>{
console.log(acc,v);
return v
}, 0)
// 0 1
// 1 2
// 2 3
// 3 4
// 4 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment