How can I store only elements that are individual values?
Example :
> ['a', 'b', 'c', 'd', 'e', 'b', 'a', 'd'] // this
> ['c', 'e'] // to this
Anyone can help me about this ?
How can I store only elements that are individual values?
Example :
> ['a', 'b', 'c', 'd', 'e', 'b', 'a', 'd'] // this
> ['c', 'e'] // to this
Anyone can help me about this ?
A solution with O(n) using reduce
and filter
.
var data = ['a', 'b', 'c', 'd', 'e', 'b', 'a', 'd']
let map = data.reduce((a,c) => (a[c] = (a[c] || 0) + 1,a),{}),
res = Object.keys(map).filter(e => map[e] == 1);
console.log(res)
First we create a map of the elements by using reduce
, counting how often they appear in the array as value for each element's key. Afterwards we take the keys with Object.keys
and apply filter
, keeping only those keys where the value is exactly 1.
You could compare first found index of element with the last one, and filter array based on those
const data = ['a', 'b', 'c', 'd', 'e', 'b', 'a', 'd'];
const result = data.filter(element => data.indexOf(element) === data.lastIndexOf(element))
console.log(result)
Simple and algorithmic approach:
In the first iteration, the count of each element is being stored as key-value pairs (The key is the actual element and the count being the value).
If the element is already in the object, we increment its count otherwise we store it with a count of 1.
In the second iteration, we push all those elements whose count is exactly 1 to a new array.
var a = ['a', 'b', 'c', 'd', 'e', 'b', 'a', 'd']
var repeating = {};
a.map(_ => {
if(_ in repeating) {
repeating[_] += 1;
} else {
repeating[_] = 1;
}
})
let nonRepeating = [];
for(var key in repeating) {
if(repeating[key] == 1) {
nonRepeating.push(key);
}
}
console.log(nonRepeating)