The idea behind the script is as follows: I am filtering the original array by removing all even values from it. Next, I form a new array from the partial products of the original array:
// new first element = 1 * 3;
// second = (first (previous multiplication) * current value) = 3 * 3 (9);
// third = (previous product * current value) = 9 * 9 (81)
I got the results I wanted, but my output doesn't look like an array:
Input:
3 3 9
Output:
3
9
81
Please help me draw the following output:
Input:
3 3 9
Output:
3 9 81
function modify(arr) {
var result = [];
arr = arr.filter(item => !(item % 2 == 0))
.reduce(function(acc, curItem) {
console.log(acc * curItem);
return acc * curItem;
}, 1)
for (let i = 0; i < result.length; i ) {
arr.push(result[i]);
};
return result;
}
console.log( modify([3,3,9]) )
CodePudding user response:
You can use reduce
keeping track of both your cumulative product, and the final array:
const input = [3, 3, 9];
const output = input.reduce( (acc,val) => {
const newResult = acc.cum * val;
acc.result.push(newResult);
acc.cum = newResult;
return acc;
},{cum:1, result:[]});
console.log(output.result);
As the last element of the array is always the cumulative product, you could also write it like this:
const input = [3, 3, 9];
const output = input.reduce( (acc,val) => {
const newResult = (acc.length ? acc[acc.length-1] : 1) * val;
acc.push(newResult);
return acc;
},[]);
console.log(output);
It's up to you which one of these you find easier to work with.
CodePudding user response:
With Array#reduce()
method and the spread
operator you can transform your array as in the following demo:
let modify = (arr) => arr.reduce((acc,cur,i) => [...acc, (acc[i-1] || 1) * cur],[]);
console.log( modify([3,3,9]) );
Or simply:
function modify(arr) {
return arr.reduce(function(acc,cur,i) {
return [...acc, (acc[i-1] || 1) * cur]
}, []);
}
console.log( modify([3,3,9]) );
Or if this is code that runs once, in which case you don't need a function:
let oldArray = [3,3,9];
let newArray = oldArray.reduce(function(acc,cur,i) {
return [...acc, (acc[i-1] || 1) * cur]
}, []);
console.log( newArray );