最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arrays - Javascript remove all occurrence of duplicate element, leaving the only one that is unique - Stack Overflow

programmeradmin0浏览0评论

I want to remove elements that occurr more than once and get the unique element. The array always has 3 elements. Lets say i have an array [2,3,2], then I need to get 3 which is only unique in the array(removing both 2s, because they occur more than once).

I have tried with following code, but surely it doesnot work as expected.

var firstArrTemp = [2,3,2];
var sorted_arr = firstArrTemp.sort();
var unique_element;
for (var i = 0; i < sorted_arr.length - 1; i++) {
    if (sorted_arr[i + 1] != sorted_arr[i]) {
        unique_element=sorted_arr[i];
    }
}

alert(unique_element);

Thanks!

I want to remove elements that occurr more than once and get the unique element. The array always has 3 elements. Lets say i have an array [2,3,2], then I need to get 3 which is only unique in the array(removing both 2s, because they occur more than once).

I have tried with following code, but surely it doesnot work as expected.

var firstArrTemp = [2,3,2];
var sorted_arr = firstArrTemp.sort();
var unique_element;
for (var i = 0; i < sorted_arr.length - 1; i++) {
    if (sorted_arr[i + 1] != sorted_arr[i]) {
        unique_element=sorted_arr[i];
    }
}

alert(unique_element);

Thanks!

Share Improve this question asked Oct 21, 2014 at 11:28 WatsMyNameWatsMyName 4,4785 gold badges48 silver badges82 bronze badges 4
  • @Vohuman, No this is not duplicate, the page you refered gives 2,3 as a resulting array, I just want to get 3, removing both 2s. Please read question carefully before marking as duplicate – WatsMyName Commented Oct 21, 2014 at 11:31
  • @vohuman: That's not what this question needs. This question asks for a result that contains all elements that are unique. – Cerbrus Commented Oct 21, 2014 at 11:31
  • @Johan, that is not what i want, please read the post again – WatsMyName Commented Oct 21, 2014 at 11:34
  • What about when array is [1,2,3] should return [1,2,3]? – laaposto Commented Oct 21, 2014 at 11:36
Add a comment  | 

10 Answers 10

Reset to default 8

This should do the trick:

Array.prototype.getUnique = function(){
    var uniques = [];
    for(var i = 0, l = this.length; i < l; ++i){
        if(this.lastIndexOf(this[i]) == this.indexOf(this[i])) {
            uniques.push(this[i]);
        }
    }
    return uniques;
}

// Usage:

var a = [2, 6, 7856, 24, 6, 24];
alert(JSON.stringify(a.getUnique()));

console.log(a.getUnique()); // [2, 7856]

To check if a specific item is unique in the array, it just checks if the first index it's found at, matches the last index it's found at.

One alternative with filter() function:

var myArray = [1,2,3,2,2,4,3,7,3].sort();
var uniqueValues = myArray.filter(function(item, i, arr) {
  return (item !== arr[i-1] && item !== arr[i+1]);
});

Where uniqueValues = [1,4,7]

The other answers so far all have O(n log n) time complexity or worse. This can be done in O(n) time though the use of Sets (Set.has has O(1) complexity) instead of nested loops:

// .sort has complexity O(n log n): it's not needed here, avoid it
const getOnlyUniques = (arr) => {
  const foundOnce = new Set();
  const foundTwice = new Set();
  arr.forEach((item) => {
    if (foundOnce.has(item)) {
      foundTwice.add(item);
    }
    foundOnce.add(item);
  });
  return arr.filter(item => !foundTwice.has(item));
};
console.log(getOnlyUniques([2, 3, 2]));

An alternative:

var a = [2,3,2], result = [];

for(var i = 0; i < a.length; i++){

    if(getAllIndexes(a, a[i]).length === 1)
        result.push(a[i]);
}

console.log(result);

function getAllIndexes(arr, val) {
    var indexes = [], i = -1;
    while (~(i = arr.indexOf(val, i+1)))
        indexes.push(i);
    return indexes;
}
const nums = [1,2,3,3,3,5,5,5];
const chars = ['a','b','a','b','a','a'];
const mixed = [1,3,'b',3,'b','a','b',3];
const unique = [1,'a',3]; 

const distinct = (arr) => arr.filter((el) => arr.filter((item) => item === el).length === 1);

console.log(distinct(nums)); // [ 1, 2 ]
console.log(distinct(chars)); // []
console.log(distinct(mixed)); // [ 1, 'a' ]
console.log(distinct(unique)); // [ 1, 'a', 3 ]
  1. first, we'll double loop over "arr" with "filter"

arr.filter((el) => arr.filter((item) => ... );

  1. if "item" is equal to "el" then return its "length"

arr.filter((el) => arr.filter((item) => item === el).length

  • this will return the occurrence count for each element in the array
  • let' use the 1st example to illustrate this:
  • [1,2,3,3,3,5,5,5] --> [1,1,3,3,3,3,3,3]
  • 1 occurred 1 time
  • 2 occurred 1 time
  • 3 occurred 3 time
  • 5 occurred 3 time
  1. to return any element that is non-repeating or unique, we just need to specified length to equal "1"

arr.filter((el) => arr.filter((item) => item === el).length === 1)

  • this approach allows you to choose the amount of occurrences from an element you want to return
  • for instance, if you you want to return an element that occurs 3 times from an array, then set the "length" to equal 3

When it comes to removing duplicates from an array I usually use one approach:

const arrWithDuplicates = [1,2,2,2,3,4,4]
const arrWithUniqueValues = [...new Set(arrWithDuplicates)]

// result will be: [1,2,3,4]

This also works with strings and booleans.

Another approach by taking a Map and set the value to false, if a key has been seen before. Then filter the array by taking the value of the map.

var array = [2, 3, 2],
    result = array.filter(
        Map.prototype.get,
        array.reduce((m, v) => m.set(v, !m.has(v)), new Map)
    );

console.log(result); // [3]

Just one line

arr.filter((item, pos, a) => a.lastIndexOf(item) === a.indexOf(item));

const arr = [1, 2, 3, 4, 1, 5, 6, 5];
const unique = arr.filter((item, pos, a) => a.lastIndexOf(item) === a.indexOf(item));
console.log(unique);

Util function

Array.prototype.unique = function() {
    return this.filter((item, pos, a) => a.lastIndexOf(item) === a.indexOf(item));
}

console.log([1, 2, 3, 4, 1, 5, 6, 5].unique());

I used the trick below to do the magic

if(A.length > 1 && A.length < 100000) {
    const unique_element = [];
    A.map((elem, index, arr) => {
        for(let i = 0; i < arr.length; i++)
        {
            if(arr.lastIndexOf(elem) === arr.indexOf(elem)) {
                unique_element.push(elem);
            }
        }
    })

    if(unique_element.length > 0) {
        alert(unique_element[0]);
    }
    else {
        alert("No unique value");
    }
}
else {
    process.exit(1);
}
const getUnique = (nums) => {
  let res = 0;
  nums.forEach((element) => {
    res = res ^ element;
  });
  return res;
};
console.log(getUnique([1, 3, 1, 3, 4])); // returns 4

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论