Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
collect "alike" elements together into sub-arrays (kinda like a partial reduce, sorta) --- and the second version shows how to not sub-array single elements "easily"
function collectLikes(arr) {
var i, j, type;
arr = Array.prototype.slice.call(arr);
for (i=0; i<arr.length; i++) {
type = typeof arr[i];
for (j=i+1; j<arr.length; j++) {
if (typeof arr[j] !== type) {
break;
}
}
arr.splice(
/*start=*/i,
/*howMany=*/j-i,
/*replace=*/arr.slice(i,j)
);
}
return arr;
}
console.log("[ ]",collectLikes([]));
// [ ]
// [ ]
console.log("[ 1 ]",collectLikes([1]));
// [ 1 ]
// [ [ 1 ] ]
console.log("[ 1, 2, 3 ]",collectLikes([1,2,3]));
// [ 1, 2, 3 ]
// [ [ 1, 2, 3 ] ]
console.log("[ 1, 2, '3', '4', '5', 6, true ]",collectLikes([1,2,'3','4','5',6,true]));
// [ 1, 2, '3', '4', '5', 6, true ]
// [ [ 1, 2 ], [ '3', '4', '5' ], [ 6 ], [ true ] ]
console.log("[ 1, '2', 3, true, false, null ]",collectLikes([1,'2',3,true,false,null]));
// [ 1, '2', 3, true, false, null ]
// [ [ 1 ], [ '2' ], [ 3 ], [ true, false ], [ null ] ]
function collectLikes(arr) {
var i, j, type;
arr = Array.prototype.slice.call(arr);
for (i=0; i<arr.length; i++) {
type = typeof arr[i];
for (j=i+1; j<arr.length; j++) {
if (typeof arr[j] !== type) {
break;
}
}
if (j > i + 1) { // <---- ADDED THIS IF
arr.splice(
/*start=*/i,
/*howMany=*/j-i,
/*replace=*/arr.slice(i,j)
);
} // <----
}
return arr;
}
console.log("[ ]",collectLikes([]));
// [ ]
// [ ]
console.log("[ 1 ]",collectLikes([1]));
// [ 1 ]
// [ [ 1 ] ]
console.log("[ 1, 2, 3 ]",collectLikes([1,2,3]));
// [ 1, 2, 3 ]
// [ [ 1, 2, 3 ] ]
console.log("[ 1, 2, '3', '4', '5', 6, true ]",collectLikes([1,2,'3','4','5',6,true]));
// [ 1, 2, '3', '4', '5', 6, true ]
// [ [ 1, 2 ], [ '3', '4', '5' ], 6, true ]
console.log("[ 1, '2', 3, true, false, null ]",collectLikes([1,'2',3,true,false,null]));
// [ 1, '2', 3, true, false, null ]
// [ 1, '2', 3, [ true, false ], null ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.