Removing duplicate element in an array [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Easiest way to find duplicate values in a JavaScript array
Javascript array sort and unique
I have the following array
var output = new array(7);
output[0]="Rose";
output[1]="India";
output[2]="Technologies";
output[3]="Rose";
output[4]="Ltd";
output[5]="India";
output[6]="Rose";
how can i remove the duplicate elements in above array.Is there any methods to do it?

You can write a function like this
function eliminateDuplicates(arr) {
var i,
len=arr.length,
out=[],
obj={};
for (i=0;i<len;i++) {
obj[arr[i]]=0;
}
for (i in obj) {
out.push(i);
}
return out;
}`
Check this here

Maybe more complex than you need but:
function array_unique (inputArr) {
// Removes duplicate values from array
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;
}
Code taken from: http://phpjs.org/functions/array_unique:346

You can remove dups from an array by using a temporary hash table (using a javascript object) to keep track of which images you've already seen in the array. This works for array values that can be uniquely represented as a string (strings or numbers mostly), but not for objects.
function removeDups(array) {
var index = {};
// traverse array from end to start
// so removing the current item from the array
// doesn't mess up the traversal
for (var i = array.length - 1; i >= 0; i--) {
if (array[i] in index) {
// remove this item
array.splice(i, 1);
} else {
// add this value to index
index[array[i]] = true;
}
}
}
Here's a working example: http://jsfiddle.net/jfriend00/sVT7g/
For sizable arrays, using an object as a temporary index will be many times faster than a linear search of the array.

First of all, you'll want to use the array literal (var output = []) to declare your array. Second, you'll want to loop through your array and store all the values in a second array. If any value in the first array matches a value in the second array, delete it and continue looping.
Your code would look like this:
var output = [
"Rose",
"India",
"Technologies",
"Rose",
"Ltd",
"India",
"Rose"
]
var doubledOutput = [];
for(var i = 0; i < output.length; i++) {
var valueIsInArray = false;
for(var j = 0; j < doubledOutput.length; j++) {
if(doubledOutput[j] == output[i]) {
valueIsInArray = true;
}
}
if(valueIsInArray) {
output.splice(i--, 1);
} else {
doubledOutput.push(output[i]);
}
}
Please note, the above code is untested and may contain errors.

Related

How can I check if a value exists in an array with multiple objects - javascript?

So my array looks like this:
let array = [
{"object1":1},
{"object2":2},
{"object3":3}
];
What I want to do is to check, for example, whether or not "object1" exists. The way I would prefer is pure Javascript.
I am doing this for large chunks of data and so my code needs to be something like this:
if ("opensprint1" in array){
console.log("yes, this is in the array");
} else {
console.log("no, this is not in the array");
};
NOTE: I have tried to use the (in) function in JS and the (hasOwnProperty) and neither has worked.
Any ideas?
if ("opensprint1" in array){
That check for the array keys, so it would work with:
if ("0" in array){
But actually you want to check if some of the array elements got that key:
if(array.some( el => "opensprint1" in el))
You're trying to filter an array of objects. You can pass a custom function into Array.prototype.filter, defining a custom search function. It looks like you want to search based on the existence of keys. If anything is returned, that key exists in the object array.
let array = [{
"object1": 1
},
{
"object2": 2
},
{
"object3": 3
}
];
const filterByKey = (arr, keyName) =>
array.filter(obj => Object.keys(obj).includes(keyName)).length > 0;
console.log(filterByKey(array, 'object1'));
console.log(filterByKey(array, 'object5'));
That is roughly equivalent to:
let array = [{
"object1": 1
},
{
"object2": 2
},
{
"object3": 3
}
];
const filterByKey = (arr, keyName) => {
// iterate each item in the array
for (let i = 0; i < arr.length; i++) {
const objectKeys = Object.keys(arr[i]);
// take the keys of the object
for (let j = 0; j < objectKeys.length; j++) {
// see if any key matches our expected
if(objectKeys[i] === keyName)
return true
}
}
// none did
return false;
}
console.log(filterByKey(array, 'object1'));
console.log(filterByKey(array, 'object5'));
This might help you
let array = [
{"object1":1},
{"object2":2},
{"object3":3}
];
let targetkey = "opensprint1";
let exists = -1;
for(let i = 0; i < array.length; i++) {
let objKeys = Object.keys(array[i]);
exists = objKeys.indexOf(targetkey);
if (exists >= 0) {
break;
}
}
if (exists >= 0) {
console.log("yes, this is in the array");
} else {
console.log("no, this is not in the array");
}
let array = [
{ "object1": 1 },
{ "object2": 2 },
{ "object3": 3 }
];
let checkKey = (key) => {
var found = false;
array.forEach((obj) => {
if (!(obj[key] === undefined)) {
found = true;
array.length = 0;
}
});
return found;
}
console.log(checkKey("object2"));
In this case, I think one of the most efficient way is to do a for and break like:
let array = [
{"object1":1},
{"object2":2},
{"object3":3}
];
exist = false;
for(let i = 0; i<array.length; i++){
if("object1" in array[i]){
exist = true;//<-- We just know the answer we want
break;//<-- then stop the loop
}
}
console.log(exist);
When iteration finds a true case, stops the iteration. We can't perform a break in .map, .filter etc. So the number of iterations are the less possible. I think this is also the case of .some()

some elements are not removed from array [duplicate]

This question already has answers here:
Remove items from array with splice in for loop [duplicate]
(5 answers)
Closed 6 years ago.
i have created an array for vowels position in string now i want reomve all elements that have value -1 from this array but its not working
function translatePigLatin(str) {
var vowelp=[];
var newarr=str.split('');
vowelp.push(newarr.indexOf('a'));
vowelp.push(newarr.indexOf('e'));
vowelp.push(newarr.indexOf('i'));
vowelp.push(newarr.indexOf('o'));
vowelp.push(newarr.indexOf('u'));
var minvowel=vowelp[0];
for(var i=0;i<vowelp.length;i++) { //looping through vowel's position array
if(vowelp[i]==-1) {
vowelp.splice(i,1);
console.log(vowelp[i]);
}
}
return vowelp;
}
input-translatePigLatin("consonant");
output that i am getting is[6,-1,1] but i want [6,1]
Simple way is to use filter()
function translatePigLatin(str) {
var vowelp = [];
var newarr = str.split('');
vowelp.push(newarr.indexOf('a'));
vowelp.push(newarr.indexOf('e'));
vowelp.push(newarr.indexOf('i'));
vowelp.push(newarr.indexOf('o'));
vowelp.push(newarr.indexOf('u'));
var minvowel = vowelp[0];
return vowelp.filter(function(v) {
return v != -1;
})
}
console.log(translatePigLatin("consonant"));
In your case you need to decrement the value of i in case of item removal otherwise it will skip the next element.
function translatePigLatin(str) {
var vowelp = [];
var newarr = str.split('');
vowelp.push(newarr.indexOf('a'));
vowelp.push(newarr.indexOf('e'));
vowelp.push(newarr.indexOf('i'));
vowelp.push(newarr.indexOf('o'));
vowelp.push(newarr.indexOf('u'));
var minvowel = vowelp[0];
for (var i = 0; i < vowelp.length; i++) { //looping through vowel's position array
if (vowelp[i] == -1) {
vowelp.splice(i, 1);
i--;
console.log(vowelp[i]);
}
}
return vowelp;
}
console.log(translatePigLatin("consonant"));
You can make it more simple using map() and filter() with an array
function translatePigLatin(str) {
return ['a', 'e', 'i', 'o', 'u'].map(function(v) {
return str.indexOf(v);
}).filter(function(v) {
return v != -1;
});
}
console.log(translatePigLatin("consonant"));
you are calling splice on the same array you are iterating over. Rememeber splice is mutable and it deletes from the original array. As a result of that your index tracking logic is getting messed up. So instead you could use delete[i] (which does not mess up the indexes and creates a void)
function translatePigLatin(str) {
var vowelp=[];
var newarr=str.split('');
vowelp.push(newarr.indexOf('a'));
vowelp.push(newarr.indexOf('e'));
vowelp.push(newarr.indexOf('i'));
vowelp.push(newarr.indexOf('o'));
vowelp.push(newarr.indexOf('u'));
var minvowel=vowelp[0];
for(var i=0;i<vowelp.length;i++) { //looping through vowel's position array
if(vowelp[i]==-1) {
delete vowelp[i];
}
}
return vowelp;
}
console.log(translatePigLatin("consonant")); //prints [6, 3: 1]
which means you have 6 at index 0 and 1 at index 3
I would prefer a simpler code:
function translatePigLatin(str) {
var vowelp = [];
var vowels = ['a','e','i','o','u'];
for (var i = 0; i < vowels.length; i++) {
var index = str.indexOf(vowels[i]);
if (index != -1) {
vowelp.push(index);
}
}
return vowelp;
}

Find and show duplicated value [duplicate]

This question already has answers here:
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
(97 answers)
Closed 9 years ago.
Any idea how to get this:
var MyArr = [0,1,2,3,"something",44,661,3,1,"something"]
var Results = [1,3,"something"]
I just want to find duplicated values in my array.
Use a for loop:
var Results = [];
MyArr.forEach(function(el, idx){
//check if value is duplicated
var duplicated = MyArr.indexOf(el, idx + 1) > 0;
if(duplicated && Results.indexOf(el) < 0) {
//duplicated and not in array
Results.push(el);
}
});
Solution with O(n) time and O(n) space. Example:
Results = duplicates(MyArr);
Using map data structure. Works only if there are strings or numbers in MyArr;
function duplicates(input) {
var results = [],
_map = {};
for (var i in input) {
if (typeof _map[input[i]] == "undefined") {
_map[input[i]] = 1;
}
else {
_map[input[i]]++;
}
}
for (var argument in _map) {
if (_map[argument] > 1) {
results.push(argument);
}
}
return results;
}
PS: Because _map[input[i]] takes O(1) time because it is a hash table, but indexOf() takes O(n) time.
PS2: Another solution with lower constant:
function duplicates(input) {
var results = [],
_map = {};
WAS = 1,
SKIP = -1;
for (var i in input) {
if (typeof _map[input[i]] == "undefined") {
_map[input[i]] = WAS;
}
else if (_map[input[i]] == WAS) {
_map[input[i]] = SKIP;
results.push(input[i]);
}
}
return results;
}
You could store each value in a new array, and before adding a new item to such array check if it already exists, and get the results back. Example using Array.forEach():
var myArr = [1,2,3,2];
var results = [];
myArr.forEach(function(item) {
if (results.indexOf(item) < 0) {
results.push(item);
}
});
If you just want the duplicated values, you could use a very similar approach and make use of Array.filter.
Note: beware that Array.indexOf() does not work on IE8, for example, you could use jQuery.inArray() method
You can mimic a counted set by using an object whose properties are elements of the set and whose values are the number of occurrences. So you can convert your array to a counted set and read off the elements that have a count of two or more. (This works only if the elements of MyArr are strings or numbers.)
So try this:
var counts = {} ;
MyArr.forEach(function(el){
counts[el] = counts[el]==undefined ? 1 : counts[el]+1 ;
});
var Results = Object.keys(counts).filter(function(el){
return counts[el] > 1 ;
}) ;

Get object's index from an array [duplicate]

This question already has answers here:
Getting index of an array's element based on its properties
(7 answers)
Closed 9 years ago.
My array looks something like this:
var someArray =
[
{ id: 'someID', name: 'someName', title: 'someTitle' },
{ id: 'anotherID', name: 'anotherName', title: 'anotherTitle' },
{ id: 'otherID', name: 'otherName', title: 'otherTitle' }
];
I want to get index reference of an object that who's id === 'anotherID' in reference with someArray
I know that I can use $.grep() to return an object:
var resultArray = $.grep(columns, function(e){return e.id === 'anotherID'});
resultArray will return an array of objects that match the condition of anonymous function, but it will not return an index of that object in someArray
I am looking for JavaScript/Jquery solution.
Thank you.
A simple for:
var elementIndex = false;
for ( var index = 0, length = someArray.length; index < length; index++ ) {
if ( someArray[index].id === 'anotherID' ) {
elementIndex = index;
break;
}
}
if ( elementIndex !== false ) {
console.log(elementIndex);
}
The easiest way is going to be to write your own function (unless you have access to the built-in indexOf method and it works for you:
var indexOf = function(array, predicate) {
for(var i = 0; i < array.length; i++) {
if(predicate(array[i])) {
return i;
}
}
return -1;
}
Which you could then call like:
var index = indexOf(someArray, function(e){ return e.id === 'anotherID'; });
.reduce() is not supported by IE8
One liner using reduce:
someArray.reduce(function(p,c,i){return c.id=='anotherID'?i:p},-1);
Using jQuery's $.each:
var posIndex = '';
$.each(someArray, function(i){
if(someArray[i].id === 'anotherID'){
posIndex = i;
return false; /*Stop iterating once found. Tip from Felix Kling*/
}
});
See example fiddle (upper code part).
As you see, using jQuery is alot easier than normal JS for.
This answer considers that each id is really an identifier (a.k.a. unique) or else posIndex will return the position of the last object which has anotherID.
Update
Added 'Felix Kling' tip of return false;. Now it will return the first match only. If have more than one id with same value, use below. Thanks Felix.
If you think that might have multiple equal ids, I suggest that posIndex becomes an array and then you read the array later. Example:
var posIndexArray = [];
$.each(someOtherArray, function (i) {
if (someOtherArray[i].id === 'anotherID') {
posIndexArray.push(i);
}
});
And posIndexArray will be a comma separated list of indexes you can then use $.each on it to do whatever you want with the indexes.
See example fiddle (lower code part).
You can achieve this pretty easily using either plain ol' JavaScript or jQuery if you so choose!
le vanilla
function getById(id, objects) {
for (var i = 0, length = objects.length; i < length; i++) {
if (objects[i].id === id) {
return i;
}
}
return -1;
}
jQueryyy
function getById(id, objects) {
var index = -1;
$.each(objects, function(i) {
if (this.id === id) {
index = i;
return false;
}
});
return index;
}
From that point, you could just call your little handy-dandy helper function and check that you got a good index.
var index = getById('otherId', someArray);
if (~index) {
doSomethingAwesome(someArray[index]);
}

Remove duplicates from an array using javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Remove duplicates from an array of objects in javascript
I'm trying to remove any duplicates in an array. For example if I have 112233 I want to return only 123.
My code:
function array_unique(array) {
var array_length = array.length;
var new_array = [];
for (var i = 0; i < array_length; i++) {
if (array[i] == array[i + 1]) {
}
new_array.push(array[i]);
}
return new_array;
}
I don't know what to type in the if so I can remove the doubles
Here you can remove the duplicates with complexity O(n).
var elems = {},
arr = [1,2,1,1,2,3,3,3,3,4];
arr = arr.filter(function (e) {
if (elems[e] === undefined) {
elems[e] = true;
return true;
}
return false;
});
I use the elems hash (object) to remember all already existing elements. If the current element is a key in the elems hash I just filter it.
Use prototype for Array like this
Array.prototype.removeDups = function(){
var local_array = this;
return local_array.filter(function(elem, pos) {
return local_array.indexOf(elem) == pos;
});
}
arrayWithNoDuplicates = new_array.filter(function(element, position) {
return myArray.indexOf(element) == position;
})
fxnUniqOptns = function (array) {
var oOptns = [];
$.each(array, function (i, val) {
if ($.inArray(val, oOptns) == -1)
oOptns.push(val);
});
oOptns = oOptns.sort();
return oOptns;
}
give array.splice(i, 1) after the if condition,this will remove the current element,so that duplicates will be removed.

Categories