admin管理员组文章数量:1125579
I have a requirement to add previous value of an array element with the current element and ignore zero value in between. I need this logic using javascript, Below is the example code:
var arr = [1,2,0,0,3,0,4];
// Output I need: [1,3,0,0,6,0,10];
Can we achieve something this? Thanks
Below is the code that i am using, I am not able to ignore the zero value in the array list
var durations = [1, 4.5,0,0, 3];
var sum = 0;
var array = durations.map(value => sum += value);
console.log(array);
// Output I am getting: [ 1, 5.5, 5.5, 5.5, 8.5 ]
// Output I need: [1,5.5,0,0,8.5]
I have a requirement to add previous value of an array element with the current element and ignore zero value in between. I need this logic using javascript, Below is the example code:
var arr = [1,2,0,0,3,0,4];
// Output I need: [1,3,0,0,6,0,10];
Can we achieve something this? Thanks
Below is the code that i am using, I am not able to ignore the zero value in the array list
var durations = [1, 4.5,0,0, 3];
var sum = 0;
var array = durations.map(value => sum += value);
console.log(array);
// Output I am getting: [ 1, 5.5, 5.5, 5.5, 8.5 ]
// Output I need: [1,5.5,0,0,8.5]
Share
Improve this question
edited Jan 9 at 7:02
JSON Derulo
17.2k11 gold badges56 silver badges73 bronze badges
asked Jan 9 at 6:56
HariHari
11 silver badge1 bronze badge
New contributor
Hari is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
0
4 Answers
Reset to default 1You can check the current value of loop in .map()
and return 0 if the value is 0:
var arr = [1, 4.5, 0, 0, 3];
var sum = 0;
var result = arr.map(value => value ? sum += value : 0);
console.log(result);
You can use something like this:
let arr = [ 1, 2, 0, 0, 3, 0, 4 ];
let previous = arr[ 0 ];
for( let i = 1; i < arr.length; i ++ ) {
if( arr[ i ] != 0 ) {
arr[ i ] = arr[ i ] + previous;
previous = arr[ i ];
}
}
console.log( arr );
You could use the &&
operator to either evaluate to 0 (when the first operand is 0) or an updated sum:
const sumUp = (arr, sum=0) => arr.map(value => value && (sum += value));
// Demo
const arr = [1, 4.5, 0, 0, 3];
const result = sumUp(arr);
console.log(result);
You could use Array#reduce()
:
const arr = [1,2,0,0,3,0,4];
const r = arr.reduce((r, item) => (r.arr.push(item ? r.prev = item + (r.prev ?? 0) : item), r), {arr: []}).arr;
console.log(JSON.stringify(r));
本文标签:
版权声明:本文标题:javascript - Add previous value of an array element with the current element and ignore zero value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736667098a1946721.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论