返回仅出现一次的数字(JavaScript)

时间:2016-08-30 09:36:28

标签: javascript

说我有阵列[1,2,3,5,2,1,4]。如何让JS返回[3,4,5]

我在这里查看了其他问题,但他们都是关于删除多次出现的数字副本,而不是原始副本和副本。

谢谢!

4 个答案:

答案 0 :(得分:2)

两次使用 Array#filter 方法。

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);

或使用 Array#indexOf Array#lastIndexOf 方法的其他方式。

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);

答案 1 :(得分:1)

您也可以使用.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);

如果您检查newArr,则其值为:

[3, 4, 5]

答案 2 :(得分:0)

var arr = [1,2,3,5,2,1,4]
var sorted_arr = arr.slice().sort(); // You can define the comparing function here. 
var nonduplicates = [];
var duplicates=[];
for (var i = 0; i < arr.length; i++) {
    if (sorted_arr[i + 1] == sorted_arr[i]) {
        duplicates.push(sorted_arr[i]);
    }else{
        if(!duplicates.includes(sorted_arr[i])){
        nonduplicates.push(sorted_arr[i]);
      }
    }
}

alert("Non duplicate elements >>"+ nonduplicates);
alert("Duplicate elements >>"+duplicates);

答案 3 :(得分:0)

我认为Map可能存在选项。

function unique(array) {
  // code goes here
  const myMap = new Map();
  for (const el of array) {
    // save elements of array that came only once in the same order
    !myMap.has(el) ? myMap.set(el, 1) : myMap.delete(el);
  }
  return [...myMap.keys()];
}

const array = [1,2,3,5,2,1,4];
//[11, 23, 321, 300, 50, 23, 100,89,300];

console.log(unique(array));