This question already has answers here:
forEach on array of undefined created by Array constructor
(5 answers)
Closed 6 years ago.
Array(3) yields [ , , ], which has a length of 3.
[1, 2, 3].forEach loops 3 times, as expected.
Neither Array(3).forEach nor [ , , ].forEach loops at all, however.
Why is this? I thought I'd discovered a way of doing something n times without using for loops, and am disappointed to find it doesn't work!
forEach() executes the provided callback once for each element present
in the array in ascending order. It is not invoked for index
properties that have been deleted or are uninitialized (i.e. on sparse
arrays)
Example from MDN:
Fiddle
function logArrayElements(element, index, array) {
console.log('a[' + index + '] = ' + element);
}
// Notice that index 2 is skipped since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9
Have a look at MDN article.
.
Related
This question already has answers here:
Javascript Concatenate Array to String
(2 answers)
Closed 2 years ago.
My goal is to make numbers into strings.
If my actual = concatenateNumbers(7);
expected = "7"
My code for this would be:
function concatenateNumbers(num1) {
return num1.toString();
}
However, if my actual has 2 or 3 more values, actual = concatenateNumbers(7, 9) or actual = (7, 9 ,1) => the expected is = "79" or "791"
Can anybody give me an idea or hint on how I should approach this?
Use The arguments object converted to a real Array, and use Array.prototype.join() with an empty String:
function concatenateNumbers() {
return [...arguments].join("");
}
var numbersArrays = [
[],
[7],
[7, 9],
[7, 9, 1]
];
numbersArrays.forEach(numbersArray=>{
console.log(numbersArray.join(", ") + " => " + concatenateNumbers(...numbersArray));
});
console.log("1, 2, 3 => "+concatenateNumbers(1, 2, 3));
numbersArrays is just a convenient way to use SO's code snippet, along with "["+numbersArray.join(", ")+"]" to show each numbersArrays's Array as an Array, plus the actual call to the actual function concatenateNumbers.
Edited to make function's arguments actually a list of Numbers using the Spread syntax (...), as pointed out by VLAZ.
It will actually concatenate anything, the best it can...
This question already has answers here:
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
(97 answers)
Closed 2 years ago.
let us consider an array
let array=["a","b","c","d","a"]
a is already present in the array, how to return true/false for this condition.
i don't want to do this
let value=array.includes("a")
in this case i know a is repeated so i use includes("a"). How to write a generic solution to find if an item is repeated in an array .(imagine getting an array from an api, so u wont know what will be repeated )
Well you can use the .indexOf and .lastIndexOf to do that, so the idea is if both return the same index of the item then it's not repeated and it's unique but if the index is different then there are at least two copies of the item, so we can write a small function to do that given the array to search in and the item to search for
var x = [1, 6, 4, 6, 3, 2, 1];
function isRepeated(arr, n) {
return arr.indexOf(n) !== arr.lastIndexOf(n);
}
console.log("1 is repeated? " + isRepeated(x, 1));
console.log("3 is repeated? " + isRepeated(x, 3));
console.log("6 is repeated? " + isRepeated(x, 6));
console.log("4 is repeated? " + isRepeated(x, 4));
This question already has answers here:
How to get first N number of elements from an array
(14 answers)
Closed 5 years ago.
i would like to get the first 3 elements of an array of variable length. i've sorted my array and i would like to get a Top 3.
here's what i've done :
var diffSplice = this.users.length - 1;
return this.users.sort(this.triDec).splice(0,diffSplice)
my "solution" work only for an array of 4 element ( -1 )
Is there a better way to use the splice method ?
Thanks for your help
You could use Array#slice for the first three items.
return this.users.sort(this.triDec).slice(0, 3);
Don't you want to use a const value for diffSplice like
var diffSplice = 3;
return this.users.sort(this.triDec).slice(0,diffSplice)
try running
let arr = [1, 2, 3, 4, 5];
console.log(arr.slice(0, 3));
refer to Array Silce
Fill out the deletecount for Splice:
var sortedArray = this.users.sort(this.triDec);
return sortedArray.splice(0, 3);
check MDN
This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 5 years ago.
I wrote a function in javaScript that checks if it is the first time the numbers has been seem, if so, it will be added to the the array. For some reason the first number is always repeating it, Ex:
if we pass [1,1,1,2,3,3,4,5]
it will print out [1,1,2,3,4,5] instead of [1,2,3,4,5]
Could anyone tell me what I'm missing ??
Thank you in advance.
var numbers = [1,1,1,1,1,2,3,4,4,4,5,5,6,6,6,8];
function eliminateDup(arr){
var myArr = [];
for(var i = 0;i<arr.length;i++){
if(!myArr[arr[i]]){
myArr.push(arr[i]);
}
}
return myArr;
}
console.log(eliminateDup(numbers));
This comparison doesn't make sense :
if(!myArr[arr[i]]){
It is true only if !myArr[arr[i]] can be converted to true.
You get twice 1 in the target array myArr because both arr[0] and arr[1] equals to 1 and myArr has an undefined element at the 1 index for the two first iterations at the time where the conditional statement is executed.
First iteration
i = 0
arr[0] = 1
myArr[1] = undefined
So if(!myArr[1]) is true.
You add 1.
Second iteration
i = 1
arr[1] = 1
myArr[0] = 1 // now valued but not used in the test
myArr[1] = undefined;
So if(!myArr[1]) is true.
You still add 1.
Third iteration
i = 2
arr[2] = 1
myArr[0] = 1
myArr[1] = 1
So if(!myArr[1]) is false.
nothing is added.
You should rather check whether the current value is not contained in the target array before adding it in the target array :
if(myArr.indexOf(arr[i])==-1){
myArr.push(arr[i]);
}
use this condition instead, for push
if(myArr.indexOf([arr[i])===-1)
myArr.push(arr[i]); will push to back of the array myArr (just like a stack) and thus element '1' will be at index 0.
myArr[arr[i]] checks if element at index arr[i] exists which it won't so will push another 1.
As suggested above use indexof() which will just search and give an index if the element exists.
This question already has answers here:
Why does javascript turn array indexes into strings when iterating?
(6 answers)
Is a JavaScript array index a string or an integer?
(5 answers)
Why is key a string in for ... in
(3 answers)
When iterating over values, why does typeof(value) return "string" when value is a number? JavaScript
(1 answer)
Closed 1 year ago.
I've simplified my program down to this, and it's still misbehaving:
var grid = [0, 1, 2, 3];
function moveUp(moveDir) {
for (var row in grid) {
console.log('row:');
console.log(row + 5);
}
}
It seems that row is a string instead of an integer, for example the output is
row:
05
row:
15
row:
25
row:
35
rather than 5, 6, 7, 8, which is what I want. Shouldn't the counter in the for loop be a string?
Quoting from MDN Docs of for..in,
for..in should not be used to iterate over an Array where index order
is important. Array indexes are just enumerable properties with
integer names and are otherwise identical to general Object
properties. There is no guarantee that for...in will return the
indexes in any particular order and it will return all enumerable
properties, including those with non–integer names and those that are
inherited.
Because the order of iteration is implementation dependent, iterating
over an array may not visit elements in a consistent order. Therefore
it is better to use a for loop with a numeric index (or Array.forEach
or the non-standard for...of loop) when iterating over arrays where
the order of access is important.
You are iterating an array with for..in. That is bad. When you iterate with for..in, what you get is the array indices in string format.
So on every iteration, '0' + 5 == '05', '1' + 5 == '15'... is getting printed
What you should be doing is,
for (var len = grid.length, i = 0; i < len; i += 1) {
console.log('row:');
console.log(grid[i] + 5);
}
For more information about why exactly array indices are returned in the iteration and other interesting stuff, please check this answer of mine
You should use a normal for loop rather than a for...in loop for arrays.
for (var row = 0, l = grid.length; row < l; row++) {
console.log('row:');
console.log(5 + row);
}
I think this is what your expected output should be.
Fiddle
Try with parseInt(..) method to force int value
console.log(parseInt(row,10) + 5);
second param 10 is to be parsed as decimal value.
See the answer here How do I add an integer value with javascript (jquery) to a value that's returning a string?