This question already has answers here:
Why is using "for...in" for array iteration a bad idea?
(28 answers)
Closed 6 years ago.
In the following code why is i treated as a string? I have to multiple it by 1 to get it to convert back to a number.
getPositionInArray(value, array) {
console.log('array = ', array);
let i = 0; // why is i a string?
for (i in array) {
if (array[i].toLowerCase() === value) {
let positionOnUI = i * 1 + 1; // why can't I use i + 1?
return positionOnUI;
}
}
return null;
}
just use a normal for loop and you wont have this issue:
Working Example
function getPositionInArray (value, array) {
console.log('array = ', array);
for (let i = 0; i < array.length; i++) {
if (array[i].toLowerCase() === value) {
let positionOnUI = i // why can't I use i + 1?
return positionOnUI;
}
}
return null;
}
assuming the array is an array...
the problem is for(i in array) that treats the array as an object and return the indexes as strings:
change the loop in for(;i<array.length;i++) and it should work.
Related
This question already has answers here:
Why does map() return an array with undefined values?
(1 answer)
Why does having [].map with curly brackets change the way it works?
(4 answers)
Closed 4 years ago.
When is run this, its printing undefined. while doing the ret.push(func(arr[i])) it does have the context right ?
function print(arr,func){
var ret =[]
for(let i =0 ;i<arr.length;i++){
ret.push(func(arr[i]))
}
return ret;
}
var numbers = [1,2,3,4,5];
console.log(print(numbers,(x)=>{x+1}));
it prints [undefined,undefined,undefined,undefined,undefined].
You could take a return statement and get the new values.
function print(arr, func) {
var ret = [];
for (let i = 0; i < arr.length; i++) {
ret.push(func(arr[i]));
}
return ret;
}
var numbers = [1, 2, 3, 4, 5];
console.log(print(numbers, (x) => { return x + 1; }));
// ^^^^^^
// or take a simplified lambda with implicit return (kudos paul!)
console.log(print(numbers, x => x + 1));
This question already has answers here:
Check if an array contains duplicate values [duplicate]
(17 answers)
Closed 6 years ago.
"Rows":[
[0:"2017-01-01", 1:"Ontdekkingstocht"],
[0:"2017-01-01", 1:"Ontdekkingstocht"],
[0:"2017-01-02", 1:"Ontdekkingstocht"]]
How do I check if 0:"2017-01-01" appears more than once, and if so, return true?
Here's a fast way:
var data = {
"Rows": [
["2017-01-01", "Ontdekkingstocht"],
["2017-01-01", "Ontdekkingstocht"],
["2017-01-02", "Ontdekkingstocht"]
]
};
function dupes(data) {
var cnt = {};
data.Rows.forEach((i) => { cnt[i[0]] = 1 });
return Object.keys(cnt).length < data.Rows.length;
}
console.log(dupes(data));
Here a fonction doing that, with your array as parameter:
function checkDuplicate(arr){
var i = 0;
while(i < arr.length-1){
arr.slice(i+1).forEach(function(element) {
if(element[0] == arr[i][0])return true;
});
}
return false;
}
A fast readable way is:
const rows = [
["2017-01-01", "Ontdekkingstocht"],
["2017-01-01", "Ontdekkingstocht"],
["2017-01-02", "Ontdekkingstocht"]
];
const duplicates = rows
.reduce((prev, curr) => [...prev, ...curr])
.some((element, index, array) => array.filter(el => element === el));
console.log(duplicates);
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;
}
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 ;
}) ;
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.