Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (13.1k points)

I was trying to run a snippet code which will help me to get all the unique numbers present in an array. But the code is not running properly, if an array consists of 0. Can anyone help me with the code:

Array.prototype.getUnique = function() {

 var o = {}, a = [], i, e;

 for (i = 0; e = this[i]; i++) {o[e] = 1};

 for (e in o) {a.push (e)};

 return a;

}

1 Answer

0 votes
by (26.7k points)

Basically, if you are using JavaScript then, you can use the filter method to get all the unique values in an array:

function Unique(value, index, self) {

  return self.indexOf(value) === index;

}

// usage example:

var a = ['a', 1, 'a', 2, '1'];

var unique = a.filter(Unique);

console.log(unique); // ['a', 1, 2, '1']

I hope this will help.

Want to become a Java expert? join Java Course now!!

Want to know more about Java? Watch this video on Learn Java | Java Programming for Beginners:

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Feb 20, 2021 in Java by Jake (7k points)

Browse Categories

...