I've the following data:
var array = [2, 4, 12, 4, 3, 2, 2, 5, 0];
I want to sum 2 + 4 + 12 + 3 + 5
and want to show the result using JavaScript without any library, by simply using a for
loop and if
/ else
statements.
you can try following using Set and Array.reduce
var array = [2,4,12,4,3,2,2,5,0]; let set = new Set(); let sum = array.reduce((a,c) => { if(!set.has(c)) {set.add(c); a += c; } return a; }, 0); console.log(sum);
const distinct = (array) => array ? array.reduce((arr, item) => (arr.find(i => i === item) ? [...arr] : [...arr, item]), []) : array; const sum = distinct([2,4,12,4,3,2,2,5,0]).reduce((a,b) => a + b); console.log(sum);
Here is a simple solution using a loop:
const array = [2, 4, 12, 4, 3, 2, 2, 5, 0]; function sumNotCommon(array) { const sortedArray = array.slice().sort(); let sum = 0; for (let i = 0; i < sortedArray.length; ++i) { if (i === 0 || sortedArray[i] !== sortedArray[i-1]) sum += sortedArray[i]; } return sum; } console.log(sumNotCommon(array));
First it sorts the array and then iterates through it ignoring equal numbers that follow each other.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.