0

How to delete element from indexed array based on value

Example:

var add = { number1: 'hello' , number2: "Haii", number3: "Byee" };

Now I want to delete element which having value Haii.

Can we do it with out iterate using for loop.

3 Answers 3

2
var add = {
    number1: 'hello',
    number2: "Haii",
    number3: "Byee"
};

for (var x in add) {
    if (add[x] == "Haii") {
        add[x].remove();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Can we do it with out iterate using fir loop.

  1. First, get all the keys which correspond to the value Haii.

    var filteredKeys = Object.keys(add).filter(function(currentKey) {
        return add[currentKey] === "Haii";
    });
    
  2. Then, delete all those keys from add

    filteredKeys.forEach(function(currentKey) {
        delete add[currentKey];
    });
    

No explicit looping at all :-)

We can reduce the above seen two step process into a one step process, like this

Object.keys(add).forEach(function(currentKey) {
    if (add[currentKey] === "Haii") {
        delete add[currentKey];
    }
});

Again, no explicit looping :-)

Comments

1
var add = {
    number1: 'hello',
    number2: "Haii",
    number3: "Byee"
};

for (var i in add) {
    if (add[i] == "Haii") {
        delete add[i];
    }
}

try this:

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.