1

I have an array

var myArray = ['1','1','2','2','1','3'] // 6 item

Is there any ways I can return the value of 1 and 2 and 3 ONE time when looping?

//example in pseudocode
var getNumber = [];
var count = 0;
var check = 0;

for(var i in myArray)
{
     if(getNumber[check] !== myArray[i])
     {    
          getNumber[count] = myArray[i];
          count++;
     }
     else
     {

     }
}

and advice to follow up my previous code?

thanks

Charlie
  • 22,886
  • 11
  • 59
  • 90
shin1234
  • 217
  • 1
  • 3
  • 12

5 Answers5

0

you could do something like :

function leaveDupes(arry){
  var newArry = [], keys={};
  for(var i in arry){
    if(!keys[arry[i]]){
      newArry.push(arry[i]);
      keys[arry[i]]=true;
    }
  }
  return newArry;
}

console.log(leaveDupes(['1','1','2','2','1','3'] ))

using underscore.js, you can do something like:

newArry = _.uniq(['1','1','2','2','1','3']);
mido
  • 24,198
  • 15
  • 92
  • 117
0

You should use Array.indexOf and Array.push to check and insert values.

var getNumber = [];

for(var i in myArray)
{
     if(getNumber.indexOf(myArray[i]) < 0)    //See if the number wasn't found already
     {    
          getNumber.push(myArray[i]);

     }
     else
     {
           //This number was found before. Do nothing!
     }
}
Charlie
  • 22,886
  • 11
  • 59
  • 90
0
var obj = {};
for (var i = 0; i < myArray.length; i++) {
    if (!obj[myArray[i]]) {
        obj[myArray[i]] = true;
        console.log(myArray[i]); //these are the unique values
    }
}
0

This will work.

var myArray = ['1','1','2','2','1','3']
var getNumber = {};
var retArray = [];

myArray.forEach(function(val){
  if(!getNumber[val]){
    getNumber[val] = val;
    retArray.push(val);
  }
});

return retArray
0

You can use forEach and indexOf array method to find the unique elements.

var myArray = ['1','1','2','2','1','3','4','4','5'];
   var uniqueArray =[]; //A new array which will hold unique values
   function _unique(myArray){
     myArray.forEach(function(item,index){
       if(uniqueArray.indexOf(item) ==-1){  //Check if new array contains item
        uniqueArray.push(item)
       }
     })

   }
 _unique(myArray);
brk
  • 48,835
  • 10
  • 56
  • 78