This question already has answers here:
How to get value at a specific index of array In JavaScript?
(8 answers)
Closed 11 months ago.
I have a foreach loop for an array, with an index to tell me which loop i am on, and an item to tell me the value of the loop i am on. Probably an obvious answer, but I'd like to be able to get the item from the index. How might i do this?
const bar1beats = [1, 0.5, 0.5, 2]
bar1beats.forEach(foreachfunction);
function foreachfunction(item, index1){
checkitemof(index1 - 1)
}
The forEach function callback can accept three arguments - the item, the index, and the array itself.
function foreachfunction(item, index1, theArray){
if (index1 > 0) {
const previousItem = theArray[index1 - 1];
...
}
}
Related
This question already has answers here:
Why does this forEach return undefined when using a return statement
(5 answers)
Function with forEach returns undefined even with return statement
(5 answers)
Short circuit Array.forEach like calling break
(30 answers)
Closed 7 years ago.
$('button').click(function () {
[1, 2, 3, 4, 5].forEach(function (n) {
if (n == 3) {
// it should break out here and doesn't alert anything after
return false
}
alert(n)
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click me</button>
My question: Why does it still alert next number although I call return? Just like: Ignore the code below and continue with next element
From the Mozilla Developer Network:
There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.
Early termination may be accomplished with:
A simple loop
A for...of
loop
Array.prototype.every()
Array.prototype.some()
Array.prototype.find()
Array.prototype.findIndex()
The other Array methods: every(), some(), find(), and findIndex() test the array elements with a predicate returning a truthy value to determine if further iteration is required.
The return exits the current function, but the iterations keeps on, so you get the "next" item that skips the if and alerts the 4...
If you need to stop the looping, you should just use a plain for loop like so:
$('button').click(function () {
var arr = [1, 2, 3, 4, 5];
for(var i = 0; i < arr.length; i++) {
var n = arr[i];
if (n == 3) {
break;
}
alert(n);
})
})
You can read more about js break & continue here: http://www.w3schools.com/js/js_break.asp
This question already has answers here:
How to check if an array is empty or exists?
(23 answers)
Closed 2 years ago.
Please write a function called lastElement which accepts a single array argument. The function should return the last element of the array (without removing the element). If the array is empty, the function should return null.
lastElement([3,5,7]) //7
lastElement([1]) //1
lastElement([]) //null
** the code that I wrote **
let array = [3, 5, 7];
function lastElement (array) {
return array[array.length - 1];
}
I'm flummoxed on the last part with the function returning null if the array if empty.
You can update your code a tiny bit to check if the array is empty and then return null like this:
return array.length ? array[array.length - 1] : null;
This question already has answers here:
JavaScript "new Array(n)" and "Array.prototype.map" weirdness
(14 answers)
How to create an array containing 1...N
(77 answers)
Closed 2 years ago.
I am trying to create an Array using new Array() and filling with index + 1 but somehow, though array is creating successfully but values are not filling correctly.
Code -
var aa = (new Array(4)).map((x, index) => {
return index + 1;
});
console.log(aa);
Output - [undefined, undefined, undefined, undefined]
Expected - [1, 2, 3, 4]
Let me know what I am doing wrong here.
map only visits entries that actually exist, it skips gaps in sparse arrays.
There are various ways to do this:
You can use Array.from and its mapping callback:
const as = Array.from(Array(4), (_, index) => index + 1);
console.log(as);
You can use a simple for loop:
const as = [];
for (let index = 1; index <= 4; ++index) {
as.push(index);
}
console.log(as);
You can use fill and then map:
const as = Array(4).fill().map((_, index) => index + 1);
console.log(as);
A variant of fill+map, you can use spread as Igor shows.
[...Array(4)].map((v, i) => i + 1)
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:
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.
.