Skip to content

Instantly share code, notes, and snippets.

@getify
Last active January 1, 2016 07:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save getify/8109596 to your computer and use it in GitHub Desktop.
Save getify/8109596 to your computer and use it in GitHub Desktop.
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