0

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);
    }
2
  • 2
    Show us some of those ways that you've tried. Commented Jul 31, 2015 at 17:02
  • I am not sure if the down vote was a great answer to a question, I didnt post code because it wasnt working, but I updated my question. Thanks Commented Jul 31, 2015 at 17:07

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

That worked perfectly, thank you sir, you have saved me a lot of frustration. Ty
1

This function has your desired functionality:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.