How to find a unique element in an array?

Alex Gail asked 11 months ago

There is an array with one unique value.

var opis = [“tseremonii”, “tseremonii”, “fotografy”, “fotografy”, “mesto-provedeniya”, “makiyazh-i-pricheska”, “makiyazh-i-pricheska”]

How can you find this unique value on pure JS?
In this array, the result should be: mesto-provedeniya
Only it does not have a duplicate.

5 Answers
Best Answer
Holland answered 11 months ago


function unique (value, index, self) {
return self.filter ((item) => item === value) .length === 1;
}

opis.filter (unique);
// ["mesto-provedeniya"]

Martin answered 11 months ago
function uniq (arr) {
  const store = arr.reduce ((acc, cur) => {
    ! acc [cur]? acc [cur] = 1: acc [cur] ++
    return acc
  }, {})
  Return Object.keys (store) .filter (key => store [key] === 1)
}

Kventin answered 11 months ago

Create a dictionary where the line corresponds to the number of its references in the array. Then from it take only those keys for which the number of mentions == 1.
const counts = opis.reduce ((p, c) => {p [c] = p [c]? p [c] +1: 1; return p;}, {});
const result = [];
for (let k in counts) if (counts [k] === 1) result.push (k);

Harry Booth answered 11 months ago

He asked, he answered, here is the solution

function getUniqueElems (A) // A is an ordered array.
{
var n = A.length, B = [];
for (var i = 1, j = 0, t; i <n + 1; i ++)
{if (A [i-1] === A [i]) t = A [i-1];
if (A [i-1]! == t) B [j ++] = A [i-1];
}
// At the output, the array with only those elements of the input
return B; // ordered array that do not have duplicates.
}

Cameron answered 11 months ago


function uniq (arr) {
const store = arr.reduce ((acc, cur) => {
! acc [cur]? acc [cur] = 1: acc [cur] ++
return acc
}, {})
Return Object.keys (store) .filter (key => store [key] === 1)
}