Array Not Indexing Correctly

Asked by At

request_people is originally '254,,one,one,one,99,,one,one,ORCHARD,one,ON,one/255,254,TWO,TWO,TWO,99' which is transformed to:

request_people
    array(2): {
       [0]:  array(13): {
          [0]:  string(3): "254"
          [1]:  string(0): ""
          [2]:  string(3): "one"
          [3]:  string(3): "one"
          [4]:  string(3): "one"
          [5]:  string(2): "99"
          [6]:  string(0): ""
          [7]:  string(3): "one"
          [8]:  string(3): "one"
          [9]:  string(7): "ORCHARD"
          [10]:  string(3): "one"
          [11]:  string(2): "ON"
          [12]:  string(3): "one"
       }
       [1]:  array(6): {
          [0]:  string(3): "255"
          [1]:  string(3): "254"
          [2]:  string(3): "TWO"
          [3]:  string(3): "TWO"
          [4]:  string(3): "TWO"
          [5]:  string(2): "99"
       }
    }

I want to redefine the array by shifting the first element for an index to being the actual index.

So the output should be:

new_request_people
    array(2): {
       [254]:  array(12): {
          [0]:  string(0): ""
          [1]:  string(3): "one"
          [2]:  string(3): "one"
          [3]:  string(3): "one"
          [4]:  string(2): "99"
          [5]:  string(0): ""
          [6]:  string(3): "one"
          [7]:  string(3): "one"
          [8]:  string(7): "ORCHARD"
          [9]:  string(3): "one"
          [10]:  string(2): "ON"
          [11]:  string(3): "one"
       }
       [255]:  array(5): {
          [0]:  string(3): "254"
          [1]:  string(3): "TWO"
          [2]:  string(3): "TWO"
          [3]:  string(3): "TWO"
          [4]:  string(2): "99"
       }
    }

I have the following code:

request_people = request_people.split('/');
for (i = 0; i < request_people.length; i++)
{
    request_people[i] = request_people[i].split(',');
}
//dump(request_people, 'alert');
var new_request_people = new Array();
for (i = 0; i < request_people.length; i++)
{

    var key = parseInt(request_people[i][0]);
    new_request_people[key] = request_people[i];
    dump(new_request_people, 'alert');
}

As a side note, it seems to make the array the size of the given value (69) and adds 'test' at the very end.

1 Answers

2
Nina Scholz On Best Solutions

You could build a new array and take the first value as index for the rest of the inner arrays.

The result is a sparse array with two elements.

var data = '254,,one,one,one,99,,one,one,ORCHARD,one,ON,one/255,254,TWO,TWO,TWO,99',
    result = data
        .split('/')
        .map(s => s.split(','))
        .reduce((r, [index, ...array]) => (r[index] = array, r), []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }