1

How do i delete the 'test1' from db using the del function?

var db = [];
function add(input) {
  for(var key in db) {
    if(db[key][0]===input[0]) {
      return;
    }
  }
  db[db.length] = input;
}

function edit(input, upgrade) {
  for(var key in db) {
    if(db[key][0]===input) {
      db[key] = upgrade;
    }
  }
}

function del(input) {
  var index = db.indexOf(input);
  if (index !== -1) {
    db.splice(index, 1);
  }
}

add(['test1', 'online']);
console.log(db);

edit('test1', ['test1','offline']);
console.log(db);

del('test1'); // FAILED still shows old values
console.log(db);

1 Answers1

0

The actual problem is not with the splice but with the indexOf. It will return the index of the item, only if the item being searched is the same as the object in the array. So, you have to roll your own search function, like this

function del(input) {
    var i;
    for (i = 0; i < db.length; i += 1) {
        if (db[i][0] === input) {
            db.splice(i, 1);
            return;
        }
    }
}

Note: Never iterate an array with for..in. Use normal for loop.

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497