0

I have an array articles that has arrays results. I am attempting to combine all these results into one array without the results for example:

const articles = [{ "id": 203, "title": "testing"}, {"id": 213,"title": "new title"}, { "id": 1, "title": "one"}, {"id": 2,"title": "two"}, { "id": 32, "title": "test article"}, {"id": 62,"title": "title test"}]

I've attempted to achieve this by mapping articles but the return result are still separate arrays instead of 1 array of objects. How can I achieve this?

Here is my code snippet:

const articles = [{results: [{ "id": 203, "title": "testing"}, {"id": 213,"title": "new title"}]}, {results: [{ "id": 1, "title": "one"}, {"id": 2,"title": "two"}]}, {results: [{"id": 62,"title": "title test"}]} ]



let mappedArticles = articles.map(article => {
    return article.results
})
console.log(mappedArticles)

0

2 Answers 2

3

You can use flatMap

const articles = [{results: [{ "id": 203, "title": "testing"}, {"id": 213,"title": "new title"}]}, {results: [{ "id": 1, "title": "one"}, {"id": 2,"title": "two"}]}, {results: [{"id": 62,"title": "title test"}]} ]

let mappedArticles = articles.flatMap(article => article.results)
console.log(mappedArticles)

Sign up to request clarification or add additional context in comments.

Comments

0

In case flatMap is not supported by your environment, there is another way to achieve it, although a bit more verbose and non-trivial, which uses the concat method of the Array prototype:

const articles = [{results: [{ "id": 203, "title": "testing"}, {"id": 213,"title": "new title"}]}, {results: [{ "id": 1, "title": "one"}, {"id": 2,"title": "two"}]}, {results: [{"id": 62,"title": "title test"}]} ]

const mappedArticles = articles.reduce((acc, article) => acc.concat(article.results), []);

console.log(mappedArticles);

Comments

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.