Question: Merge or Combine two different size arrays and filling gaps with 0

Question

Merge or Combine two different size arrays and filling gaps with 0

Answers 1
Added at 2016-12-21 10:12
Tags
Question

I have two arrays and I want to merge or combine, but first compare to see if similar values exist and then fill the gaps with 0, but must conserve first array order. like the example:

Array1: 1 2 3 4 5 6
Array2: 2 5

NewArray: 0 2 0 0 5 0

I read about combining arrays but not sure about how to replace missing rows with 0 and keeping same order of the first Array...

Answers to

Merge or Combine two different size arrays and filling gaps with 0

nr: #1 dodano: 2016-12-21 10:12

Assuming you want to store result in "result" array.

Objective-C version:

NSArray *arr1 = @[@1,@2,@3,@4,@5,@6];
NSArray *arr2 = @[@2,@5];

NSMutableArray *result = [NSMutableArray array];

for (NSNumber * item in arr1){
    [arr2 containsObject: item] ? [result addObject:item] : [result addObject:@0];
}

Swift version:

let arr1 = [1,2,3,4,5,6]
let arr2 = [2,5]

let result = arr1.map { x -> Int in
    return arr2.contains(x) ? x : 0
}
Source Show
◀ Wstecz