ios - Swift 3: sum value with group by of an array of objects -


i have code in viewcontroller

var myarray :array<data> = array<data>() in 0..<mov.count {        myarray.append(data(...)) }  class data {     var value :cgfloat     var name  :string=""     init({...}) } 

my input of data as:

  • 10.5 apple
  • 20.0 lemon
  • 15.2 apple
  • 45

once loop through, return new array as:

  • sum(value) group name
  • delete last row because no have name
  • ordered value

expected result based on input:

  • 25.7 apple
  • 20.0 lemon
  • and nothing else

i wrote many rows of code , confused post it. i'd find easier way, has idea this?

first of data reserved in swift 3, example uses struct named item.

struct item {     let value : float     let name  : string } 

create data array given values

let dataarray = [item(value:10.5, name:"apple"),                   item(value:20.0, name:"lemon"),                   item(value:15.2, name:"apple"),                   item(value:45, name:"")] 

and array result:

var resultarray = [item]() 

now filter names not empty , make set - each name occurs 1 once in set:

let allkeys = set<string>(dataarray.filter({!$0.name.isempty}).map{$0.name}) 

iterate thru keys, filter items in dataarray same name, sum values , create new item total value:

for key in allkeys {     let sum = dataarray.filter({$0.name == key}).map({$0.value}).reduce(0, +)     resultarray.append(item(value:sum, name:key)) } 

finally sort result array value desscending:

resultarray.sorted(by: {$0.value < $1.value}) 

Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -