0

This code currently searches the result array for where the name is "abc" and removes the entire index. How can I make it so it checks for name contains "abc". ie. name could be "abcd" and would still be removed.

var i;
for (i = result.length; i--;) {
  if (result[i].name === "abc") { 
    result.splice(i, 1);
  }
}

result is a JSON like
[{"name": "aaa", "number": "123"},{"name": "abc", "number": "456"},{"name": "abcd", "number": "789"},]

0

2 Answers 2

7

You can use filter and include to get the result you want

 var array = [{"name": "aaa", "number": "123"},{"name": "abc", "number": "456"},{"name": "abcd", "number": "789"}]
 
 var result = array.filter(item => !item.name.includes("abc"));
 console.log(result)

Sign up to request clarification or add additional context in comments.

3 Comments

Note to OP ► .includes() does not work in Internet Explorer. Just in case you are using it.
To make it IE compatible you'd have to do something like array.filter(function(item){return item.name.indexOf("abc")});
@AndrewBone a small shim is also possible. jsfiddle.net/jhrrpcus
2
result[i].name.indexOf('abc') === 0

Essentially testing that the name starts with abc.

If you want it to just simply be in the name you can do just

result[i].name.indexOf('abc') > -1

5 Comments

"abc".startsWith("a") // true and "abc".includes("b") // true, more elegant than indexOf
starts with is a subset of contains, but not the whole set of possibilities.
@JeremyThille as Nope mentioned in the other answer, includes is not supported in IE. caniuse.com/#search=include
This works for me. Can it also be done for where the name does not include "abc"?
@albinosilver < 0 or === -1 would be the not includes conditional

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.