Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append property of struct to array using reduce

Tags:

swift

I have an array of Items

struct Item {
    var id: String
}

How can I append all the ids to an array using reduce function?

What I try:

self.items.reduce([String](), { $0.0.append($0.1.id)})

But compiler shows an error:

Contextual closure type '(_, [Item]) -> _' expects 2 arguments, but 1 was used in closure body

like image 984
Zigii Wong Avatar asked Aug 02 '17 14:08

Zigii Wong


People also ask

How do you apply reduce on array of objects?

The reduce() method executes the function for each value of the array (non-empty array) from left to right. The reduce() method has the following syntax: let arr = [];arr. reduce(callback(acc, curVal, index, src), initVal);

What is reduce () in JavaScript?

reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator. Syntax: array.reduce( function(total, currentValue, currentIndex, arr), initialValue )

How can you double elements of an array using reduce in JavaScript?

You can reduce an array into a new array. For instance, lets reduce an array of amounts into another array where every amount is doubled. To do this we need to set the initial value for our accumulator to an empty array. The initial value is the value of the total parameter when the reduction starts.

Does reduce return array?

reduce() method is a bit more flexible. It can return anything. Its purpose is to take an array and condense its content into a single value. That value can be a number, a string, or even an object or new array.


3 Answers

Try this:

items.reduce([String](), { res, item in
    var arr = res
    arr.append(item.id)
    return arr
})
like image 99
paulvs Avatar answered Oct 20 '22 14:10

paulvs


If you want to do it with reduce, here is a snippet for Swift 3 and 4:

struct Item {
    var id: String
}

var items = [Item(id: "text1"), Item(id: "text2")]
let reduceResult = items.reduce([String](), { $0 + [$1.id] } )
reduceResult // ["text1", "text2"]

There were 2 issues:

  1. Reduce is giving you 2 arguments, not single tuple with 2 values
  2. You can't edit argument that is passed to you in the block, you have to return new object

But in this case the best solution is to use map:

let reduceResult = items.map { $0.id }
like image 45
Piotr Tobolski Avatar answered Oct 20 '22 14:10

Piotr Tobolski


You probably mean map rather than reduce

let ids = items.map{ $0.id }
like image 37
vadian Avatar answered Oct 20 '22 13:10

vadian