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.

asked Dec 14, 2014 at 6:58

3 Answers 3

2
var add = {
 number1: 'hello',
 number2: "Haii",
 number3: "Byee"
};
for (var x in add) {
 if (add[x] == "Haii") {
 add[x].remove();
 }
}
thefourtheye
241k53 gold badges466 silver badges505 bronze badges
answered Dec 14, 2014 at 7:04
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 :-)

answered Dec 14, 2014 at 7:04

Comments

1
var add = {
 number1: 'hello',
 number2: "Haii",
 number3: "Byee"
};
for (var i in add) {
 if (add[i] == "Haii") {
 delete add[i];
 }
}

try this:

thefourtheye
241k53 gold badges466 silver badges505 bronze badges
answered Dec 14, 2014 at 7:03

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.