2

I have a multidimensional array

[0] {
    [0] {
        [0]: 'Element 1'
        [1]: 'Element 2'
        [2]: 'Element 3'
        [3]: 'Element 4'
    }
    [1] {
        [0]: 'Element 5'
        [1]: 'Element 6'
        [2]: 'Element 7'
        [3]: 'Element 8'
    }
    [2] {
        [0]: 'Element 9'
        [1]: 'Element 10'
        [2]: 'Element 11'
        [3]: 'Element 12'
    }
}

Now, i want to add an element between the elements 6 & 7. Currently, i'm using this

$.map($myArray, function(i, e) {
    if (i.indexOf('Element 6') >= 0) {
        $myArray.splice($.inArray('Element 6', $myArray[e]) + 1, 0, 'Element X');
    }
});

However, i'm pretty sure, that this is a suboptimal solution and that there's an easier (and more efficient) way to achieve this.

Maybe, i'm just thinking too complicated.

Huangism
  • 16,278
  • 7
  • 48
  • 74
SGL
  • 341
  • 2
  • 15
  • any how you are passing indexes to add element in between see this link might help you. http://stackoverflow.com/questions/16308252/php-add-elements-to-multidimensional-array-with-array-push any how you need to modify slite to insert into specified location. – Sudarshan Kalebere Aug 09 '14 at 07:50
  • 3
    Seeing that mix of jQuery (`inArray`) and native methods (`indexOf`) hurts my eyes… – Bergi Aug 11 '14 at 16:26

2 Answers2

4

This is more or less the good way, you can't avoid looping.

There is place for a few optimizations though :

  • don't use $.map but a standard for loop. $.map is pretty but calls a function at each step
  • use break to stop iterating when you find your item
  • don't search twice the position of the item
  • don't use $.inArray (especially as you used indexOf before)

Here's a better code :

for (var i=0; i<$myArray.length; i++) {
    var index = $myArray[i].indexOf('Element 6');
    if (~index) {
        $myArray[i].splice(index+1, 0, 'Element X');
        break;
    }
}

Simple performance comparison (note that the performance gain will depend on the data)

More generally, when you don't need compatibility with very old (and almost forgotten) browsers, and I assume you don't need that compatibility as you use indexOf, you should avoid using compatibility functions like $.map or $.inArray as they mostly add an overhead.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

should be as simple as myArray[0][1].splice(2, 0, 'Element X)

assuming that myArray is the top level array

Brad Allred
  • 7,323
  • 1
  • 30
  • 49