Condition inside forEach - javascript

I have two arrays:
firstArray = [1, 2, 3, 4];
secondArray = [5, 6, 7, 8];
I must use their elements to compute another one inside a forEach.
_.forEach(firstArray, (data, i) => {
myValue: firstArray[i] + secondArray[i]
});
This works fine. But I want to ignore the last element of the second array all the time. So in this case, for i = 3 the result should be 4, not 4+8, ignoring the last value of the second array.
I know that using an if statement wouldn't work but is there a way to do it?
I mean inside the forEach, removing the last element before the function doesn't work in this case.
UPDATE: I received some good answers but all of them were using something different than forEach. I would like to know if there is a way to do it with this function or not.

You can just check if i is the last element of the second array using array.length.
I don't really understand your forEach code, but you could use ternary operators in it:
_.forEach(firstArray, (data, i) => {
myValue: firstArray[i] + (i === secondArray.length - 1 ? 0 : secondArray[i])
});

You could reduce and map the arrays.
var firstArray = [1, 2, 3, 4],
secondArray = [5, 6, 7, 8],
result = [firstArray, secondArray].reduce((a, b) => a.map((v, i) => v + b[i]));
console.log(result);

I would do this:
firstArray = [1, 2, 3, 4];
secondArray = [5, 6, 7, 8];
for (let i = 0; i < firstArray.length; i++){
if(i === firstArray.length - 1) {
myValue = firstArray[i];
} else {
myValue = firstArray[i] + secondArray[i]
}
}

Use map
firstArray = [1, 2, 3, 4];
secondArray = [5, 6, 7, 8];
var output = firstArray.map( ( s, i, ar ) => s + (i == ar.length - 1 ? 0 : secondArray[i] ) );
UPDATE: I received some good answers but all of them were using
something different than forEach. I would like to know if there is a
way to do it with this function or not.
using forEach, you would need another array to capture the sum
firstArray = [1, 2, 3, 4];
secondArray = [5, 6, 7, 8];
var myValue = [];
firstArray.map( ( s, i, ar ) => myValue.push( s + (i == ar.length - 1 ? 0 : secondArray[i] ) ) );
now myValue is
[6, 8, 10, 4]
Hence map seems to be a less-verbose approach.

Related

How to use javascript map to combine numbers at every nth element?

I like to combine numbers at every 4th index of an array. In the following oversimplified example, I did using "for" loop. Instead of that, I like to learn how to use "map" to achieve the same result. Thanks for any help!
function test() {
var array = [1, 2, 3, 4, 5, 6, 7, 8], arrayNew = [];
for (var n = 0; n < 4; ++n)
arrayNew[n] = array[n] + array[n + 4];
console.log(arrayNew)
}
To use .map, you could iterate the slice of the array that omits the first four elements. During that iteration, the loop index will be 4 units less, so you can grab array[i] and combine it with the currently iterated value from the slice:
const array = [1, 2, 3, 4, 5, 6, 7, 8];
const result = array.slice(4).map((val, i) => array[i] + val);
console.log(result);
If you want to add more than just two values, but want to also add the value at 2n, 3n, ...etc, then you need a nested loop. Here .map is of less use. I would "map" with the use of Array.from, which has a callback function that performs a mapping. Secondly, the sum that has a dynamic number of terms can be performed with reduce:
function accumulate(array, n) {
const groups = Array.from({length: array.length / n});
return Array.from({length: n}, (val, i) =>
groups.reduce((sum, _, j) => sum + array[i + j*n], 0)
);
}
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
console.log(accumulate(array, 4));

How to map only every second value in array

I have some array of numbers:
var arr = [1, 7, 1, 4];
I want to increase only every first value, such that the expected output would be: [2, 7, 2, 4]
I tried some combination of map and filter but I don't understand how it can work together...
var mapuj = arr.map(x => x *2);
You can use map() and use second argument which is idnex to determine if it's at event index or not
let arr = [1, 7, 1, 4];
let output = arr.map((n, index) => index % 2 === 0 ? n * 2 : n);
console.log(output);

Create new loop for duplicate index with Javascript

Quick question. I need to create an array using duplicated index. For example, I have an array like:
var array = [2, 3, 2, 4, 3, 2, 6, 7];
And I need to get a new loop interaction for each duplicate index, the response should be something like:
[
[2, 3, 4, 6, 7],
[2, 3],
[2],
]
Please let me know if is possible and how to create some function to do it.
Thank you!
You can just use one object to store number of occurrences for each element and use that value to create result array.
var array = [2, 3, 2, 4, 3, 2, 6, 7];
var obj = {}, result = []
array.forEach(function(e) {
obj[e] == undefined ? obj[e] = 0 : obj[e] += 1;
result[obj[e]] = (result[obj[e]] || []).concat(e)
})
console.log(JSON.stringify(result))
you can do something like this
var array = [2, 3, 2, 4, 3, 2, 6, 7];
array.sort();
let idx = 0, result = [];
for(let i=0; i<array.length; i++){
if(i>0 && array[i] != array[i-1]){
idx = 0;
}
if(idx == result.length)
result[idx] = [];
result[idx].push(array[i]);
idx++;
}
console.log(result);

Adding pairs of numbers in array with reduce (javascript)

Given a 2D array, I want to add the last number of the preceeding inner array to the first number of the next inner array.
I managed to get up to the point where:
var output= [[1,2,3],[4,5,6],[7,8,9],[1,2,3]] //this becomes...
output = [3,4,6,7,9,1] (edited typo)
I now would like to add the pairs up to return this array:
output = [9, 11, 10]
So far, this is what I have, and it returns [3,6,4,7,9,1]. I would like to see how reduced can be used for this, but also interested in how a for loop would accomplish the same thing.
var output= [[1,2,3],[4,5,6],[7,8,9],[1,2,3]]
output = output
.reduce((newArr,currArr)=>{
newArr.push(currArr[0],currArr[currArr.length-1]) //[1,3,4,6,7,9]
return newArr
},[])
output.shift()
output.pop()
return output
Can use index argument of reduce
let output= [[1,2,3],[4,5,6],[7,8,9],[1,2,3]];
output = output
.reduce((newArr, currArr, i, origArr) => {
if (i > 0) {
let prevArr = origArr[i - 1];
newArr.push(currArr[0] + prevArr[prevArr.length - 1]);
}
return newArr
}, [])
console.log(output)
Not clear what should occur at last element of input array? You can use for..of loop, Array.prototype.entries() to sum values of specific index of arrays.
let output = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[1, 2, 3]
];
let res = Array.from({
length: output.length - 1
});
for (let [key, value] of output.entries()) {
if (key < output.length - 1)
res[key] = value[value.length - 1] + output[key + 1][0]
}
console.log(res)
You could do something like this, using reduce.
var input = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[1, 2, 3]
];
let output = [];
input.reduce((prevArr, currentArray) => {
if (prevArr) {
output.push(prevArr[prevArr.length - 1] + currentArray[0]);
}
return currentArray;
});
console.log(output);

How to iterate the contents of one array into the empty/undefined spots of another array?

I have an array:
var myArray = [2, 4, 6];
and another array:
var otherArray = [1, , 3, , 5, , 7];
I'm trying to map (or use any non "for/for-each" iterator) to place each myArray value into the corresponding empty spaces of otherArray.
Hopeful output:
newArray = [1, 2, 3, 4, 5, 6, 7];
Any ideas?
otherArray.forEach(function (val, idx) {
if (typeof val === 'undefined') {
otherArray[idx] = myArray.shift();
}
});
forEach may not be compatible if supporting IE < 9 though.
Using Array.prototype.map:
var newArray = otherArray.map(function(val) {
return typeof val === 'undefined' ? myArray.shift() : val;
});
Be aware that this will not hit indexes that have never been set.
Using while loop:
while (myArray.length > 0) {
var emptyIdx = otherArray.indexOf();
otherArray[emptyIdx] = myArray.shift();
}
Edit: Ok, if the elements in the array are truly not set, as they are in your description, these solutions won't work since they'll skip over the unset indexes. Here's one that would work:
var myArray = [2, 4, 6, 8, 9];
var otherArray = [1, , 3, , 5, , 7];
var lastIdx = -1;
otherArray.forEach(function(val, idx) {
if (idx - lastIdx > 1) {
otherArray[idx - 1] = myArray.shift();
}
});
if (myArray.length > 0) {
otherArray = otherArray.concat(myArray);
}
document.body.innerHTML = otherArray;
You can iterate through the array and check for undefined values like:
var otherArray = [1, , 3, , 5, , 7];
var myArray = [2, 4, 6];
for (var i = 0, j = 0; i < otherArray.length; i++) {
//check if a value is undefined
if (!otherArray[i]) {
//then change this value with the new from other array
otherArray[i] = myArray[j];
j++;
}
}
console.log(otherArray);//prints [1, 2, 3, 4, 5, 6, 7]
You could use recursivity, this function will fill the undefined items of the first array with the items of the second one until it reach the end of one of the arrays used.
var otherArray = [1, , 3, , 5, , 7];
var myArray = [2, 4, 6];
function fillArray(ar1, ar2, i){
if (!i) i = 0;
if (!ar1[i]){
ar1[i] = ar2.shift();
}
if (++i < ar1.length && ar2.length > 0){
fillArray(ar1, ar2, i);
}
}
fillArray(otherArray, myArray); // this will update the content of originals arrays,
// use otherArray.slice() to get a copy.
document.getElementById("result").innerHTML = JSON.stringify(otherArray);
<div id="result"></div>
If you want to add elements (because there is other items in myArray and there is no space left in otherArray) you can change the condition to continue replacing the && with ||
if (++i < ar1.length || ar2.length > 0){

Categories

Resources