Ad space (banner)
๐ŸŽObjective-C Lessons
Lesson 42 / 68

Flattening an array

This lesson covers flattening a nested array in Objective-C, with the aim of handling complicated structures simply.

When an array contains further arrays, expanding it into one flat array is called flattening. Objective-C has no dedicated method, so you implement it with a for loop and addObjectsFromArray:.

The sample code takes each nested array with for (NSArray *sub in nested) and adds them into one array with [flat addObjectsFromArray:sub]. Note how one method adds a whole array's contents at once.

A common early stumble is the difference between addObject: and addObjectsFromArray:. The first adds one element, the second adds the contents of an array — miss that and you end up with unintended nesting.

In professional work, this is a genuinely useful technique whenever nested data has to be handled as one flat list.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Objective-C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)