2

I am trying to push only distinct value in jQuery. But it is not working

var arr = [];

for (var i = 0; i < a.length; i++) {
    if (arr.indexOf({
            A: a[i].City
        }) == -1)
        arr.push({
            A: a[i].City
        });
    else
        alert("a");
}

How do i get only distinct item in array?

Bram Vanroy
  • 27,032
  • 24
  • 137
  • 239
Richa
  • 3,261
  • 2
  • 27
  • 51

2 Answers2

0

create one new array like key then insert the value of city, next you have to check it the city values is present or not

var arr = [];
var key = [];  // make one dummy array 
for (var i = 0; i < a.length; i++) {
    if (key.indexOf(a[i].City) == -1) {
        arr.push({
            A: a[i].City
        });

        key.push(a[i].City); // push value to key
    } else{
        alert("a");
    }
}
Balachandran
  • 9,567
  • 1
  • 16
  • 26
0

Try following:

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(haystack[i] == needle) return true;
    }
    return false;
}

var arr = [];

a.forEach( function(item) {
    if (!in_array(item, arr)) {
        arr.push(item);
    }
});

in_array reference: JavaScript equivalent of PHP's in_array()

It looks if an item is existing and if it's distinct (doesn't exist) it push the item into the array.

Or the jQuery solution mentioned inside the comments: Remove Duplicates from JavaScript Array

Which is following:

var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
var uniqueNames = [];
$.each(names, function(i, el){
    if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});

I posted the codes to ensure that someone finding this inside google finds some actual code and not just links that maybe are already down or closed.

Community
  • 1
  • 1
Cagatay Ulubay
  • 2,491
  • 1
  • 14
  • 26