Multiplying elements in arrays using the forEach function - javascript

I'm currently learning about arrays and the different ways to manipulate them. I was asked to: "multiply 5 to the given array using the forEach function"
Here is my code so far.
It looks as if everything works when I console.log in the forEach function, but when I log the console for the array it's read as undefined.
let multiplyArray = [1, 11, 7, 3, 8, 2, 3, 2, 10, 3, 6, 2, 5];
function multiplyNumbers() {
let numbers;
multiplyArray.forEach(function(element) {
let fiveTimesNum;
fiveTimesNum = (element * 5);
element = fiveTimesNum;
console.log(element)
});
console.log('The array(element) value is read out correctly, but when I console log the array its value is ↓')
return numbers
}
multiplyArray = (multiplyNumbers());
console.log(multiplyArray);

From the task, it seems like you're supposed to update the given array. With a forEach loop you can reference the array you are looping on along with the index and value
let multiplyArray = [1, 11, 7, 3, 8, 2, 3, 2, 10, 3, 6, 2, 5];
multiplyArray.forEach(function(val, i, arr){
arr[i] = val*5;
})

If you want to change the array multiplyArray in place you can it like this:
let multiplyArray = [1, 11, 7, 3, 8, 2, 3, 2, 10, 3, 6, 2, 5];
multiplyArray.forEach(function(n,i,a){a[i]=5*n;});
console.log(multiplyArray);

Numbers was never defined correctly, please see example below.
You can use your mapped array to return the correct data.
let multiplyArray = [1, 11, 7, 3, 8, 2, 3, 2, 10, 3, 6, 2, 5];
function multiplyNumbers() {
multiplyArray.forEach(function(element) {
let fiveTimesNum;
fiveTimesNum = (element * 5);
element = fiveTimesNum;
console.log(element)
});
console.log('The array(element) value is read out correctly, but when I console log the array its value is ↓')
return multiplyArray
}
multiplyArray = (multiplyNumbers());
console.log(multiplyArray);

Related

Get every second element of array with array methods

for learning purposes I want to get every second element of an array. I succeeded with a for loop:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function filterEverySecond(arr) {
let everySecondEl = [];
for (let i = 0; i < arr.length; i += 2) {
everySecondEl.push(arr[i]);
}
return everySecondEl;
}
console.log({
numbers,
result: filterEverySecond(numbers)
});
Now I want to achieve the same without a for loop, but by using array methods (forEach, filter, map or reduce). Can anyone recommend which method would be best here?
you can do it easily with filter
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const filtered = numbers.filter((_, i) => i % 2 === 0)
console.log(filtered)
you just filter out the elements that have a odd index
You can use filter and check if the index of the current array element is divisible by 2:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log({
numbers,
result: numbers.filter((_, index) => index % 2 === 0)
});
You can use filter for index.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log({
numbers,
result: numbers.filter((n,i)=>i%2==0)
});
You could use a for each loop like so to get the same desired output:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const result = [];
numbers.forEach(number => {
if (number % 2 != 0) {
result.push(number);
}
});
console.log(numbers);
console.log(result);
The modulus operator returns the remainder of the two numbers when divided. For example: 1 % 2 will return 1 as the remainder. So in the if statement we are checking if the number is not divisible by 2.

method to check if a specific number with a group of numbers exists within an array in javascript

var numbers = [1, 2, 3, 4, 5, 6, 7, 8];
need to check if 2, 3, 4 exist in the array. Only has to be 1 of these numbers to return true...not all. What's the best approach. I was thinking lodash includes, but I believe I can only pass in a single value.
Using Array#some and Array#includes:
const hasAny = (arr = [], nums = []) =>
nums.some(n => arr.includes(n));
console.log( hasAny([1, 2, 3, 4, 5, 6, 7, 8], [2, 3, 4]) );
If you want to get the intersection, you can filter the first array by the second array, or rather, whether or not the second array contains each element of the first. You can see which members were included, or check the size of the new array > 0 if you need a boolean (or use Mr Badawi's .some method).
var numbers = [1, 2, 3, 4, 5, 6, 7, 8];
var needs = [2, 3, 4 ];
var check = numbers.filter(x=>needs.includes(x));
console.log(check);
var numbers = [3, 5, 6, 7, 8, 12, 20];
var needs = [2, 3, 4 ];
var check = numbers.filter(x=>needs.includes(x));
console.log(check);

javascript Delete from array between 2 indices

With an array of: [1, 2, 3, 4, 5, 6]
I would like to delete between 2 indices such as 2 and 4 to produce [1, 2, null, null, 5, 6]. What's the easiest way to do this?
Hopefully better than this:
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
let i = 2;
const rangeEnd = 9;
while (i < rangeEnd) {
delete array[i];
i++;
}
console.log(array)
If you want to use some native API you can actually do this with splice(). Otherwise, you should iterate a for loop through your array and change the value in each iteration.
Here is an example of how it would be done:
const array = [1, 2, 3, 4, 5, 6]
array.splice(3, 2, null, null) // the First element is beginning index and the second is count one will indicate how many indexes you need to traverse from the first one, then you should provide replace element for each of them.
console.log(array)
Note: For more info about it you can read more here.
There is a possible workaround for large scale replacement, so I will give it a touch here:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var anotherArr = Array(2).fill(null); // or you can simply define [null, null, ...]
Array.prototype.splice.apply(arr, [3, anotherArr.length].concat(anotherArr));
console.log(arr);
As you mean the range (2, 4] so you can follow this:
The range is: lower limit exclusive and the upper limit inclusive.
const arr = [1, 2, 3, 4, 5, 6];
const deleteRange = (arr, f, t) => {
return arr.map((item, i) => {
if (i + 1 > f && i + 1 <= t) {
return null;
}
return item;
})
}
console.log(deleteRange(arr, 2, 4));

Looping over the last few entries of an array

I'm trying to have a forEach loop over an array, but only the last few entries.
I'd know how to do this in a for loop, that'd look a bit like this:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
/* This will loop over the last 3 entries */
for(var x = arr.length; x >= 7; x--){
console.log(arr[x]);
}
Would there be any way of achieving the same results in a forEach loop?
You can use slice() and reverse() methods and then forEach() loop on that new array.
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.slice(-3).reverse().forEach(e => console.log(e))
This is how you do it with forEach loop:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.forEach((element, index) => {
if(index>7) console.log(arr[index]);
})
You could take a classic approach by taking the count of the last elements and use it as counter and an offset for the index.
Then loop with while by decrementing and checking the counter.
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
last = 3,
offset = array.length - last;
while (last--) {
console.log(array[last + offset]);
}

Java Script. Add new value to end of an array and shift the rest

I would like to know what is the best way to add a new value to an end of an array and let the rest of values to shift with the first element of an array to be deleted.
Example. I got an array:
int []a = {1, 2, 3, 4, 5, 6};
and after adding 7 i want to have this:
int []a = {2, 3, 4, 5, 6, 7};
var a = [ 1, 2, 3, 4, 5, 6];
console.log('a before:- ', a)
a.push(7);
var removed = a.shift(); // Save removed item if you need it
console.log('a after:- ',a);
You can use splice method for remove element
var arr = [ 1, 2, 3, 4, 5, 6];
arr.push(7);
arr.splice(0, 1);
console.log(arr)
Output
[2,3,4,5,6,7]
for more information read this splice

Categories

Resources