0

Basically, I want to scan some array which contain a key word inside, for example:

arr = [ {"name":"apple", "count": 2},
{"name":"orange", "count": 5},
{"name":"pear", "count": 3},
{"name":"orange 356", "count": 16},
{"name":"orange fsa", "count": 15},]

I would like to get orange, orange 356 and orange fsa. I have tried to use different method of Jquery to get my function done.

var newArr = arr.filter(function(item){
    return item.name == "orange"; // tried = and === but no luck 
});
console.log("Filter results:",newArr);

and alternative:

    var newArr = [];

for(var i= 0, l = arr.length; i< l; i++){
    if(arr[i].name = "orange" ){
    newArr.push(arr[i]);
        }
    }
  console.log("Filter results:",newArr);

But it only returns the arr[1] for me, how may I able to get everything contains "orange"?

Solution:

    var newArr = [];

var newArr = arr.filter(function(item){
    return item.eman.indexOf("orange")!=-1; 

});

document.getElementById("123").innerHTML = "Filter results:"+JSON.stringify(newArr);
Anson Aştepta
  • 1,125
  • 2
  • 14
  • 38
  • You named the source array as `Arr` while referring to it in your function as `arr` – Nikolay Ermakov Feb 28 '16 at 04:19
  • Possible duplicate of [How can I check if one string contains another substring?](http://stackoverflow.com/questions/1789945/how-can-i-check-if-one-string-contains-another-substring) – Abhijeet Feb 28 '16 at 05:11
  • thanks for the remind, i have modify it , and if it's really a duplicate i should delete this duplicate. – Anson Aştepta Feb 28 '16 at 05:23

2 Answers2

1

Use String.prototype.indexOf() which will return index of the search string, if it is greater than 0, it means search string is present in the string.

Try this:

var arr = [{
  "name": "apple",
  "count": 2
}, {
  "name": "orange",
  "count": 5
}, {
  "name": "pear",
  "count": 3
}, {
  "name": "orange 356",
  "count": 16
}, {
  "name": "orange fsa",
  "count": 15
}]

var newArr = arr.filter(function(item) {
  return item.name.indexOf("orange") > -1;
});
console.log(newArr);
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
Rayon
  • 36,219
  • 4
  • 49
  • 76
1

You can use String indexOf function, for example, instead of:

return item.name == "orange";

You do:

return item.name.indexOf("orange") != -1;

The string indexOf() method returns the position of the first occurrence of a specified search term in a string and it returns -1 if the search term is not found.

Peter Pei Guo
  • 7,770
  • 18
  • 35
  • 54