How do I remove repeated elements within a vector / stack / array in javascript?
I have for example:
var array = ['foo', 'bar', 'foo'];
and I want to remove all duplicates to get:
['foo', 'bar']
How do I remove repeated elements within a vector / stack / array in javascript?
I have for example:
var array = ['foo', 'bar', 'foo'];
and I want to remove all duplicates to get:
['foo', 'bar']
You can use this:
var arr = ['foo', 'bar', 'foo'];
var novaArr = arr.filter(function(este, i) {
return arr.indexOf(este) == i;
})
console.log(novaArr); //dá ['foo', 'bar']
What this code does is use .filter () . In this native function only the elements that give return
with boolean value true
pass. And what the function checks is whether the position of each element within the array is the same as the index that the function passes.
That is, arr.indexOf(este)
gives the position / index of this element in the array, and the variable i
that the function passes does the same. If they are equal then this element is "original" ie it is the first time it appears. In case of a duplicate, the value of i
will match the position of the duplicate, but the arr.indexOf(este)
will give the position of the first time this value appears in the array.
This function is +/- recent and Internet Explorer only supports from version 9. In the link that I put up there is an alternative to IE8. Unfortunately IE7 is too old and as it has no prototype this solution does not apply.
To do with pure JavaScript, as answered in this link: link
uniqueArray = myArray.filter(function(elem, pos, self) {
return self.indexOf(elem) == pos;
})
a = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
b = {};
for (var i = 0; i < a.length; i++) {
b[a[i]] = a[i];
}
arr = [];
for (var key in b) {
arr.push(key);
}
It is a data dictionary that when the key already exists the value is simply overwritten and thus avoiding redundancy because the key is always unique in data dictionaries. Then the array is populated with the values contained in the previously populated dictionary.
Font : link
The most performative way is to convert the vector into a dictionary, and then convert to vector again.
function Foo (vetor) {
var dicionario = {};
for (var i = 0; i < vetor.length; i++) {
dicionario[vetor[i] + ""] = true;
}
var novoVetor = [];
for (var chave in dicionario) {
novoVetor.push(chave);
}
return novoVetor;
}
This technique prevents you from wasting time with searches in the vector. You simply write each value in the dictionary - and if a certain value is repeated% of% times, it will be overwritten n
times.
Note that the n - 1
value in the dictionary keys is just an arbitrary value. It could be true
, 0
, and I believe that in most cases even 1
will work, since we will ignore this value and only import the key;)
Editing: I just saw that my answer is just a more verbosic version of Venatci's answer. Kudos to him.
I think it's worth leaving a third alternative , part of the PHPJS which aims to bring to the JS resources present in PHP. In this case, a port function array_unique () :
function array_unique(inputArr) {
// discuss at: http://phpjs.org/functions/array_unique/
// original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
// input by: duncan
// input by: Brett Zamir (http://brett-zamir.me)
// bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// bugfixed by: Nate
// bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// bugfixed by: Brett Zamir (http://brett-zamir.me)
// improved by: Michael Grier
// note: The second argument, sort_flags is not implemented;
// note: also should be sorted (asort?) first according to docs
// example 1: array_unique(['Kevin','Kevin','van','Zonneveld','Kevin']);
// returns 1: {0: 'Kevin', 2: 'van', 3: 'Zonneveld'}
// example 2: array_unique({'a': 'green', 0: 'red', 'b': 'green', 1: 'blue', 2: 'red'});
// returns 2: {a: 'green', 0: 'red', 1: 'blue'}
var key = '',
tmp_arr2 = {},
val = '';
var __array_search = function (needle, haystack) {
var fkey = '';
for (fkey in haystack) {
if (haystack.hasOwnProperty(fkey)) {
if ((haystack[fkey] + '') === (needle + '')) {
return fkey;
}
}
}
return false;
};
for (key in inputArr) {
if (inputArr.hasOwnProperty(key)) {
val = inputArr[key];
if (false === __array_search(val, tmp_arr2)) {
tmp_arr2[key] = val;
}
}
}
return tmp_arr2;
}
If Chrome 31+, Firefox 13+, IE 11: (Safari: not supported).
Use Set (ECMAScript6).
var arr = [1,1,2,2,3,3,"teste","teste"];
var arr_unique = [...new Set(arr)];
Do not try objects!
Sources for further research:
I do not have much experience with programming and I started to migrate from Java to JS and I think I brought the damn inheritance of verbosity in the code, I have no idea of the performance of this algorithm below, but it worked to solve an exercise here .
function limpaValoresRepetidos(array){
for(let i in array){
let valorComparado = array[i]
let cont = 0 //contador de incidencia de repeticao, seu valor deve ser 1
for(let i in array){
if(valorComparado === array[i]){
cont +=1
if(cont > 1){
cont --
delete array[i]
}
}
}
}
return array
}