Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javaScript to return a new array of paired values from an array of single values [duplicate]

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 ]];
});
like image 895
RyanP13 Avatar asked May 04 '12 21:05

RyanP13


People also ask

How do you find duplicate numbers in an array if it contains multiple duplicates JavaScript?

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.

How do you return a duplicate element from an array?

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.

How do you check if an array of objects has duplicate values in JavaScript?

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.


3 Answers

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 ]]];
});
like image 131
McGarnagle Avatar answered Oct 01 '22 13:10

McGarnagle


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));
}
like image 29
Jonathan M Avatar answered Oct 01 '22 12:10

Jonathan M


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

like image 38
Neysor Avatar answered Oct 01 '22 12:10

Neysor