3

I want to take an array of any length (in this example length of 10):

var fruits = ["Banana", "Orange", "Apple", "Mango", "Strawberry", "Lime", "Kiwi", "Melon", "Pineapple", "Date"];

From this array I want to take elements in increments of 5, convert each increment into a string, then store each string as a nested array within a new array. Each element will need to be seperated by a '%'.

An output like:

newArray = [[ 'Banana%Orange%Apple%Mango%Strawberry' ],[ 'Lime%Kiwi%Melon%Pineapple%Date' ]]

To convert into a string I'm using:

var finalArray = Array()
    var x = ""
        for(i = 0; i < fruits.length; i++){
            if(i==fruits.length-1){
                x = x + fruits[i].toString()
            }
            else {
                x = x + fruits[i].toString()+'%'
            }       
        } finalArray.push([x])

Which outputs:

[['Banana%Orange%Apple%Mango%Strawberry%Lime%Kiwi%Melon%Pineapple%Date']]

I've attempted many for & forEach loops, if/else statements etc. in an effort to split the original array into increments of 5 before applying the string conversion code but have not been successful.

Any help or ideas on how to achieve would be appreciated. Thanks.

EDIT: Thanks all, this has answered my question :)

Harsh Patel
  • 6,334
  • 10
  • 40
  • 73
Rumpo
  • 41
  • 1
  • 4

5 Answers5

6

You can make use of Array#splice and just crop the array until it's empty:

var fruits = ["Banana", "Orange", "Apple", "Mango", "Strawberry", "Lime", "Kiwi", "Melon", "Pineapple", "Date"];

var result = [];

while (fruits.length) {
  result.push([fruits.splice(0, 5).join('%')]);
}

console.log(result);
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
2

You could slice the array and join it with the wanted separator.

This approach does not mutate the given data.

var fruits = ["Banana", "Orange", "Apple", "Mango", "Strawberry", "Lime", "Kiwi", "Melon", "Pineapple", "Date"],
    separator = '%',
    size = 5,
    index = 0,
    result = [];

while (index < fruits.length) {
    result.push([fruits.slice(index, index += size).join(separator)]);
}

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

Please, use array splice and join it with the required separator.

This approach does not mutate the existing data.

var fruits = ["Banana", "Orange", "Apple", "Mango", "Strawberry", "Lime", "Kiwi", "Melon", "Pineapple", "Date"],
separator = '%',
result = []

while (fruits.length) {
  result.push([fruits.splice(0, 5).join(separator)]);
}

console.log(result);
Harsh Patel
  • 6,334
  • 10
  • 40
  • 73
1

You can use splice() to split and join using desired string .join()

var fruits = ["Banana", "Orange", "Apple", "Mango", "Strawberry", "Lime", "Kiwi", "Melon", "Pineapple", "Date"];

function convert(array, increment, separator) {
    let result = [];
    while(array.length >= 1) {
        result.push([array.splice(0, increment).join(separator)]);
    }    
    return result;
}
console.log(convert(fruits, 5, '%'));
console.log(convert(fruits, 3, '%'));
Girish Sasidharan
  • 582
  • 1
  • 5
  • 14
0

const fruits = ["Banana", "Orange", "Apple", "Mango", "Strawberry", "Lime", "Kiwi", "Melon", "Pineapple", "Date"];
const result = []

// Loop over all the fruits.
for(let i = 0; i < fruits.length; i++){
  // Get the current fruit's sub-index.
  let idx = Math.floor(i/5);
  // Make sure the subarray exists.
  result[idx] = result[idx] || [];
  // Push the current fruit to the subarray.
  result[idx].push(fruits[i]);
}

// Now we have an nested array of arrays, you want to replace the sub-arrays with joined strings.
for(let i = 0; i < result.length; i++){
  result[i] = [result[i].join('%')];
}

console.log(result);
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • Nice effort - but this can done by doing three lines of code. by using `forEach` and `splice` to it. – Always Helping Jun 29 '20 at 07:38
  • True, but shorter code isn't always easy to understand for beginners. By cutting up the problem into small steps, The process is easier to understand, and hopefully teaches the reader some useful functions. – Cerbrus Jun 29 '20 at 07:39
  • I agree - help beginners with extra added info. – Always Helping Jun 29 '20 at 07:50