Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return numbers which appear only once (JavaScript)

Tags:

javascript

Say I have the array [1,2,3,5,2,1,4]. How do I get make JS return [3,4,5]?

I've looked at other questions here but they're all about delete the copies of a number which appears more than once, not both the original and the copies.

Thanks!

like image 827
nonono Avatar asked Apr 26 '26 06:04

nonono


2 Answers

Use Array#filter method twice.

var data = [1, 2, 3, 5, 2, 1, 4];

// iterate over elements and filter
var res = data.filter(function(v) {
  // get the count of the current element in array
  // and filter based on the count
  return data.filter(function(v1) {
    // compare with current element
    return v1 == v;
    // check length
  }).length == 1;
});

console.log(res);

Or another way using Array#indexOf and Array#lastIndexOf methods.

var data = [1, 2, 3, 5, 2, 1, 4];

// iterate over the array element and filter out
var res = data.filter(function(v) {
  // filter out only elements where both last 
  // index and first index are the same.
  return data.indexOf(v) == data.lastIndexOf(v);
});

console.log(res);
like image 147
Pranav C Balan Avatar answered Apr 27 '26 18:04

Pranav C Balan


You can also use .slice().sort()

var x = [1,2,3,5,2,1,4];
var y = x.slice().sort(); // the value of Y is sorted value X

var newArr = []; // define new Array

for(var i = 0; i<y.length; i++){ // Loop through array y
  if(y[i] != y[i+1]){ //check if value is single
    newArr.push(y[i]); // then push it to new Array
  }else{
    i++; // else skip to next value which is same as y[i]
  }
}


console.log(newArr);

If you check newArr it has value of:

[3, 4, 5]
like image 26
Luka Krajnc Avatar answered Apr 27 '26 19:04

Luka Krajnc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!