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.
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.
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.
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.
Odds and Evens Even numbers can be made into two-row arrays, but odd numbers cannot - there being always one item left over.
/**
* @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];
}
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]);
}
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