Nodejs Array Unique unique()

Here you can find the source of unique()

Method Source Code

/*//w  ww.j  a  va 2  s. co m
 Array#unique
 */
Array.prototype.unique = function() {
  return this.reduce(function(prev_val, current_val) {
    if (prev_val.indexOf(current_val) < 0) {
      prev_val.push(current_val);
    }
    return prev_val;
  }, []);
};

/*
 Array#times_do
 returns an array of n results of calling a callback
 sorta like ruby's Array.new(n) { 'val' }

 ex:
 arr = [5].times_do(function(){ return 'default value';});
 */
Array.prototype.times_do = function(callback) {
  return Array.apply(null, Array(this[0])).map(callback); // todo - add i param to callback
};

Related

  1. unique()
    Array.prototype.unique = function() {
        var a = [];
        for (var i=0, l=this.length; i<l; i++)
            if (a.indexOf(this[i]) === -1)
                a.push(this[i]);
        return a;
    };
    
  2. unique()
    Array.prototype.unique = function() {
        var a = this.concat();
        for(var i=0; i<a.length; ++i) {
            for(var j=i+1; j<a.length; ++j) {
                if(a[i] === a[j])
                    a.splice(j--, 1);
        return a;
    ...
    
  3. unique()
    Array.prototype.unique = function() {
      return this.filter(function(item, idx, array) {
        return array.indexOf(item) === idx;
      });
    
  4. unique()
    Array.prototype.unique = function(){
        var array = [];
        for(var i = 0; i < this.length; i++) {
            if(!array.contains(this[i])) {
                array.push(this[i]);
        return array.compact();
    };
    ...
    
  5. unique()
    Array.prototype.unique = function() {
      var uniques = [];
      this.forEach(function(value) {
        if (uniques.indexOf(value) == -1)
          uniques.push(value);
      });
      return uniques;
    };
    
  6. unique()
    Array.prototype.unique = function() {
        var a = [];
        for (var i = 0, l = this.length; i < l; i++)
            if (a.indexOf(this[i]) === -1)
                a.push(this[i]);
        return a;
    
  7. unique()
    Array.prototype.unique = function() {
      var a = this.concat();
      for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++j) {
          if(a[i] === a[j])
            a.splice(j--, 1);
      return a;
    ...
    
  8. unique()
    var numbers = [4,5,4,4,4,5,4,5]
    function unique(arr) {
      var newArr = [];
      for (var i = 0; i < arr.length; i++) {
        if (newArr.indexOf(arr[i]) < 0) {
          newArr.push(arr[i]);
      return newArr;
    ...
    
  9. unique()
    Array.prototype.unique = function(){
       var u = {}, a = [];
       for(var l = 0, i = this.length-1; i >= 0; --i){
          if(u.hasOwnProperty(this[i])) {
             continue;
          a.unshift(this[i]);
          u[this[i]] = 1;
       return a;
    };