w2olves
w2olves

Reputation: 2329

Removing an item from a two dimensional Javascript Array

I have a simple array like this:

  var CutRoadArray = [
            ['Location', '_Location'],
            ['Applicant Info', '_ApplicantInfo'],
            ['Details', '_ApplicationDetails'],
            ['Bond Info', '_BondInfo'],
            ['Attachments', '_Attachments'],
            ['Review', '_ReviewA']
        ];

I would like to check if this array contains the entry

['Bond Info', '_BondInfo'],

And if it does, remove it. In a separate scenario, I would like to search for the same, and if it doesnt exist, add it at a certain index.

I have tried various ways, none worked. Any help will be much appreciated.

One of the ways I have tried to accomplish this is:

Array.prototype.remove = function () {
            var what, a = arguments, L = a.length, ax;
            while (L && this.length) {
                what = a[--L];
                while ((ax = this.indexOf(what)) !== -1) {
                    this.splice(ax, 1);
                }
            }
            return this;
        };


function indexOfRowContainingId(id, matrix) {
        var arr = matrix.filter(function (el) {
            return !!~el.indexOf(id);
        });
        return arr;
    }

Then calling something like:

 var bond = indexOfRowContainingId('_BondInfo', CutRoadArray);
   if (bond.length > 0) {
                    var ar = CutRoadArray.remove("['Bond Info', '_BondInfo']");
               console.log(ar);
    }

Upvotes: 0

Views: 40

Answers (2)

BravoZulu
BravoZulu

Reputation: 1140

This function has your desired functionality:

function testArray(test, array){
    return array.filter(function(x){
        return x.toString() != test;
    })
}

testArray(['Bond Info', '_BondInfo'], CutRoadArray)

Upvotes: 1

Aravinder
Aravinder

Reputation: 503

Try this:

var CutRoadArray = [
        ['Location', '_Location'],
        ['Applicant Info', '_ApplicantInfo'],
        ['Details', '_ApplicationDetails'],
        ['Bond Info', '_BondInfo'],
        ['Attachments', '_Attachments'],
        ['Review', '_ReviewA']
    ];
var testElem = ['Bond Info', '_BondInfo'];

for(var i=0; i<CutRoadArray.length; i++){
  var temp = CutRoadArray[i].toString();
  if(temp === testElem.toString()){ 
     //remove element from array
     CutRoadArray.splice(i, 1);
     break;

  }

}

console.log(CutRoadArray);

Upvotes: 1

Related Questions