0

Assuming I have an array which looks like that:

let arr = [{field: ["alice"]}, {field : ["bob", "charlie"]}

I want to be able to concat all values without writing the nested for loops. I've done this so far:

arr.reduce((a, b) => a.field.concat(b.field))

The problem, as I see this, that the type of the array, lets say arr : Array<MyObject>, is changed when mapping or something similar.

Im getting a TS2345 error

...Is not assignable to parameter of type...

Just to clear things up, the result should be IDENTICAL to the following result.

let result = [];
for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr[i].field.length; j++) {
        result.push(arr[i].field[j])
    }
}

sorry I can't share my real code, but this is the exact issue. This works on Chrome's developer tools for some reason but not when I try to compile my code.

2
  • Just to clarify, the for loop you've added is verified to work, right? The issue is just with TS compiling the reduce function to work the same way? Commented Dec 15, 2016 at 22:33
  • the loop works, yes. the problem is caused because after one concatanation the array[0] is a different type from the others so the next reduce call wont be type safe at all. by using Map before, we choose every items to be the desired type and then invoke a function on all of them Commented Dec 15, 2016 at 22:44

2 Answers 2

2
const arr: Array<MyObject> = [{ field: ["alice"] }, { field: ["bob", "charlie"] }];

const result: Array<string> = arr.map(obj => obj.field)
                                 .reduce((a, b) => a.concat(b));
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much
0

Well, the result is going to be:

["alice", "bob", "charlie"]

when I think you want:

[{fields: ["alice", "bob", "charlie"] }]

This would be calculated with:

[{ fields: arr.reduce((a, b) => a.field.concat(b.field)) }]

2 Comments

Well the point is the difference of having an array that's a list of names, vs an array containing one object, with one parameter "fields", which contains an array that's a list of names. Sorry, may have been something you already accounted for in code that's not shown.
lets say that the objects inside the array are models/classes. I dont see how this works. Ive tried.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.