some elements are not removed from array [duplicate] - javascript

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;
}

Related

Finding if an array is in a 2D array

I want to know whether if an array is inside of a 2D array.
This is what I tried:
var x=[1,2];
var y=[[1,1],[1,2],[2,2],[3,3]];
y.includes(x); //should return true
you can create a hash:
var ar = [
[1,1],[1,2],[2,2],[3,3]
];
var hash = {};
for(var i = 0 ; i < ar.length; i += 1) {
hash[ar[i]] = i;
}
var val = [1,2];
if(hash.hasOwnProperty(val)) {
document.write(hash[val]);
}
You can do this with chained array methods!
var ar = [
[1,1],[1,2],[2,2],[3,3]
];
hasDuplicates(ar, [1,"1"]); //false
hasDuplicates(ar, [1,1]); //true
//Use some to determine at least 1 inner array matches
function hasDuplicates(array, valueToCheck) {
return array.some(function(a, i) {
//Check each inner arrays index, and verify that it equals on the same index of the array we want to check
return a.every(function(ax, ix) {
return valueToCheck[ix] === ax; //triple equals for equality!
})
});
}
Demo: https://jsfiddle.net/a3rq70hL/1/

Remove all items that have duplicates in array Javascript

I have searched on here and have not found a solution. Obviously I will be corrected if I am wrong. What I am trying to do is return values that do not have a duplicates in an array.
Examples:
myArr = [2,1,2,3] // answer [1,3]
myArr = [3,1,2,2,3] // answer [1]
I would post some code but I have not been able to figure this out myself and the only code examples I have found are for removing any duplicate values.
The possible solution above is to return no duplicates... I am trying to return values that are don't have duplicates.
One option is to use the optional second argument to indexOf to find duplicate indexes. Consider that for a given element e and an index i:
if e is the first of two identical elements in the array, indexOf(e) will return i and indexOf(e, i + 1) will return the index of the second element.
if e is the second of two identical elements in the array, indexOf(e) will return the index of the first element, and indexOf(e, i + 1) will return -1
if e is a unique element, indexOf(e) will return i and indexOf(e, i + 1) will return -1.
Therefore:
myArr.filter(function (e, i, a) {
return a.indexOf(e) === i && a.indexOf(e, i + 1) === -1
});
var isUnique = function(v,i,arr){
// return true if the first occurrence is the last occurrence
return ( arr.indexOf(v) === arr.lastIndexOf(v) );
};
var uniqueVals = myArr.filter(isUnique);
console.log( uniqueVals );
If is not an associative array (your case):
var myArr = [1,2,2,3,4,4,1,5];
var myNewArr = [];
if (myArr.length > 0 )
{
myNewArr[0] = myArr[myArr.length-1];
}
var count = 1;
myArr.sort();
for (var i = myArr.length - 2; i >= 0; i--) {
if(myArr[i] != myArr[i-1])
{
myNewArr[count] = myArr[i];
count++;
}
}
var yourArray = [1, 2, 1, 3];
var uniqueValues = [];
$.each(yourArray, function (i, value) { //taking each 'value' from yourArray[]
if ($.inArray(value, uniqueValues) === -1) {
uniqueValues.push(value); // Pushing the non - duplicate value into the uniqueValues[]
}
});
console.log(uniqueValues);
Result: [1,2,3];

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 ;
}) ;

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.

Removing duplicate element in an array [duplicate]

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.

Categories