Possible Duplicate:
Split array into chunks
I am trying to convert an array of values into a new array of paired values.
For example i need to convert:
var arr = [1,2,3,4,5,6,7,8];
into:
arr = [[1,2], [3,4], [5,6], [7,8]];
I tried using jQuery's .map() method like so but this did not work for me:
arr= $.map(arr, function(n, i){
return [n + ',' + n[ i + 1 ]];
});
Using the filter() and indexOf() Methods This is the shortest and the easiest way of finding duplicates in an array, where the filter() method traverses the array and filters items according to the defined condition and returns a new array, while the indexOf() gives the index of the passed item.
Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.
Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate.All such elements are returned in a separate array using the filter() method.
If you insist on using map, you could do it like this:
arr= $.map(arr, function(n, i){
if (i%2 === 0) return [[n, arr[ i + 1 ]]];
});
If you don't want to use a hammer on a thumbtack:
var arr = [1,2,3,4,5,6,7,8];
var newarr = new Array();
for (var i=0; i<arr.length; i=i+2) {
newarr.push(arr.slice(i,i+2));
}
don't use jquery for every problem:
var arr = [1, 2, 3, 4, 5, 6, 7, 8];
var narr = [];
for (i = 0; i < arr.length; i = i + 2) {
narr[i / 2] = [arr[i], arr[i + 1]];
}
but this only works if you have an even count of arr
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With