Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript array split at odd index

I have an array of products this contains a product name and a manufacturer, e.g. "product","manufacturer","product","manufacturer" etc..

How can I spilt the array into a separate array so that I can have the products and manufacturers in separate arrays? I want to spilt it at every odd index so that I can take the manufacture out of the array and add this into a new array?

Thanks.

like image 241
Elliott Avatar asked Mar 21 '11 21:03

Elliott


People also ask

How do you split an array by even or odd?

Logic To Split Even and Odd Elements of An Array Into Two Arrays. First we accept all the elements of an array from the user. Next we iterate through the array elements one by one using a for loop. Inside this for loop we check each individual element, if its even or odd.

How do you filter odd numbers in an array?

To find the odd numbers in an array:Use the filter() method to iterate over the array. Check if each number has a remainder when divided by 2. The filter method will return a new array containing only the odd numbers.

Can you split an array JavaScript?

Splitting the Array Into Even Chunks Using slice() Method The easiest way to extract a chunk of an array, or rather, to slice it up, is the slice() method: slice(start, end) - Returns a part of the invoked array, between the start and end indices.

Can an array have an odd number?

Odds and Evens Even numbers can be made into two-row arrays, but odd numbers cannot - there being always one item left over.


2 Answers

/**
 * @param candid Array of results
 * @return Returns an array where index 0 = array of even ones, and index 1 = array of odd ones
*/
function splitArray(candid) {
    var oddOnes = [],
        evenOnes = [];
    for(var i=0; i<candid.length; i++)
        (i % 2 == 0 ? evenOnes : oddOnes).push(candid[i]);
    return [evenOnes, oddOnes];
}
like image 121
moe Avatar answered Oct 03 '22 00:10

moe


Try with something like this:

var arr = ["product","manufacturer","product","manufacturer"];
var products = [];
var manufacturers = [];
for (var i = 0; i < arr.length; i += 2) {
    products.push(arr[i]);
    arr[i+1] && manufacturers.push(arr[i + 1]);
}
like image 27
Marcelo Avatar answered Oct 03 '22 00:10

Marcelo