0

I ask my question differently :

I'm using angular/Javacript and i want to know if a value exist in an array or not. Here's my code :

    var source = [1, 2, 3 , 4 , 5]; 
    var cities = [{ city: 4 }, { city: 6 }, { city: 8 }]; 

    angular.forEach(source, function (value, key) { 
    if (cities["city"].indexOf(value) != -1) { 
         console.log(value+ " exist"); } 
   else{ console.log(value+ " not exist"); }
 });

but the cities["city"] is not undefined. Any help ?

user708683
  • 500
  • 3
  • 9
  • 26

4 Answers4

0

Since it's an array you'll need to use an index to access the element, like so:

var firstCity = cities[0];
console.log(firstCity["city"]);
boxjar
  • 69
  • 3
0

If that's javascript, ECMAScript 6 will contain an array.find method, but for older versions, you're just going to have to loop over the cities and test each one with cities[n].city == 8.

Paul Kienitz
  • 878
  • 6
  • 25
0

Your cities array contains 3 elements. You must iterate through them and check if any of them contains the value you seek. Assuming you are using javascript, because of console.log, you could do this.

cities["city"] is undefined, because cities is an array that contains only 0,1 and 2 as indexes (cities[0], cities[1] and cities[2]). These 3 are the ones that have the index "city", like, eg, cities[0]["city"]

var source = [1,2,3,4,5];
for (var i = 0; i < source.length; i++) {

   var found = false;
   for (var j = 0; j < cities.length; j++) {
      if (cities[j]["city"] === i) {
          found = true;
      }
   }
   if (found) {
      console.log(i + " exists");
   } else {
      console.log(i + " not exists");
   }
}
brlaranjeira
  • 367
  • 2
  • 11
0

I suggest to iterate over the array with the object.

var source = [1, 2, 3, 4, 5];
var cities = [{ city: 4 }, { city: 6 }, { city: 8 }];

source.forEach(function (a) {
    if (cities.some(function (aa) { return aa.city === a; })) {
        document.write(a + ' exist<br>');
    } else {
        document.write(a + ' does not exist<br>');
    }
});

Bonus: Some ideas for use of Array.prototype.indexOf, according to the original question.

var city42 = { city: 42 };
var cities = [{ city: 4 }, { city: 6 }, { city: 8 }, city42];
document.write(cities.indexOf({ city: 8 }) + '<br>'); // -1 does not work
document.write(cities.indexOf(city42) + '<br>'); // 3 does work

var index = -1;
cities.some(function (a, i) {
    return a.city === 8 && ~(index = i);
});
document.write(index + '<br>'); // 2
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392