javascript - How to combine list elements into pairs -
is there convenient function in javascript, or without underscore.js, takes list of form [a, b, c, d]
, transforms list of form [[a, b], [b, c], [c, d]]
?
this solved array.prototype.map
:
var makepairs = function(arr) { // want pair every element next 1 return arr.map(function(current, i, arr) { // return array of current element , next return [current, arr[i + 1]] }).slice(0, -1) // every element except last, since `arr[i + 1]` `undefined` } var arr = [1, 2, 3, 4] // should never use `document.write`, except in stack snippets document.write(makepairs(arr).join("<br>"));
Comments
Post a Comment