-1
Array=[1,2,3,"abc","def","ghi",4,"jkl",5,6,"mno","pq","r","s","tu","v",2,4,55,"wx","yz"]

I want to split that array after everytime the element type changes from string to an integer.

This is the result I expect

[
    [1,2,3,"abc","def","ghi"],
    [4,"jkl"],
    [5,6,"mno","pq","r","s","tu","v"],
    [2,4,55,"wx","yz"]
]

I have tried a lot of ways but keep failing

iehrlich
  • 3,572
  • 4
  • 34
  • 43

1 Answers1

0

The following code is written in JavaScript, but can be converted to whatever language you need.

Here is a JSFiddle link to the solution working against your input array: https://jsfiddle.net/dbLaayqr/ (Note: the JSFiddle has a little extra code to output the array in a human readable form)

function split_on_type_change(input_array) {
    var output_array = [];
    var temp_array = [];
    var last_type = '';
    for (i = 0; i < input_array.length; i++) { 
        if (typeof(input_array[i]) == 'number' && last_type == 'string') {
            // append temp_array to output_array
            output_array.push(temp_array);
            // reset temp_array
            temp_array = [];
        }
        // append value to temp_array
        temp_array.push(input_array[i]);
        // keep track of the previous value's type
        last_type = typeof(input_array[i]);
    }
    // append temp_array to output_array
    output_array.push(temp_array);
    return output_array;
}
Rich G
  • 256
  • 2
  • 8