sum ONLY unique array

  • A+
Category:Languages

first of all i am sorry if this an easy question, but iam having a difficulties to select only unique array in my program (i am just learning javasript btw). i know i can easily do this with built in function like filter or map, but i am forbidden to do that. This is what i"ve got so far :

function countUnique (numbers) {  var sorted_numbers = numbers.sort(function(a,b){return a-b}) var result = [] for (var i = 0 ; i<numbers.length; i++){ if (numbers[i]!==numbers[i+1]){   result.push(numbers[i])   console.log(result) } } var sum = 0 for (var j = 0; j<result.length; j++) { sum = sum + result[j] }  return sum }  console.log(countUnique([ 5, 5, 6, 6, 3, 1, 2, 7, 7])) // 6 console.log(countUnique([ 3, 6, 3, 6, 1, 1, 2, 1 ]))  // 2 console.log(countUnique([ 3, 3, 3, 3, 4, 5, 8, 10, 11 ])) // 38 

Example: input: [ 5, 5, 6, 6, 3, 1, 2, 7, 7 ] proses: 3 + 1 + 2 result: 6

 


Use indexOf and lastIndexOf. If the result of the indexOf is equal to the result of the lastIndexOf it means that the element is unique in the array.

let arr = [ 3, 3, 3, 3, 4, 5, 8, 10, 11 ]; let sum = 0; arr.forEach(a => {   sum += (arr.indexOf(a) === arr.lastIndexOf(a)) ? a : 0; }); console.log(sum);

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: