Last active
February 20, 2022 11:53
-
-
Save dgolosov/5a38be245130c0df689be97781a33ee7 to your computer and use it in GitHub Desktop.
Working with arrays in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The most perfomance way to populate a new array | |
[...Array(1000)].map((_, i) => i); // [0,...,999] | |
// Grouping array elements by condition | |
function groupBy(list, groupingCondition) { | |
const groups = []; | |
let currentGroup = []; | |
for (const item of list) { | |
if (currentGroup.length) { | |
const lastGroupItem = currentGroup[currentGroup.length - 1]; | |
if (groupingCondition(item, lastGroupItem)) { | |
currentGroup.push(item); | |
} else { | |
groups.push(currentGroup); | |
currentGroup = [item]; | |
} | |
} else { | |
currentGroup = [item]; | |
} | |
} | |
if (currentGroup.length) { | |
groups.push(currentGroup); | |
} | |
return groups; | |
} | |
const sample = [0, 1, 2, 3, 40, 50, 51, 52]; | |
groupBy(sample, (a, b) => b === a - 1) | |
// [[0, 1, 2, 3], [40], [50, 51, 52]] | |
groupBy(sample, (a, b) => b === a - 1).map(l => l[0] + (l.length > 1 ? `-${l[l.length - 1]}` : '')).join(', ') | |
// "0-3, 40, 50-52" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment