DEV Community

Mr.Morsalin
Mr.Morsalin

Posted on

style={{whiteSpace:"pre-line"}}

Querying Nested Arrays

To work with tree data structure we need to flatten them.

We will be solving a problem using Array.prototype.forEach().
We will define Array.prototype.concatAll() using Array.prototype.forEach().
We will solve the same problem using Array.prototype.concatAll()

This post is a follow up post of the
– Getting started Functional Programming in JavaScript. I would recommend reading that post first.
Enter fullscreen mode Exit fullscreen mode

Problem

Flatten the movieLists array into an array of video ids

Let’s solve with Array.prototype.forEach()
Enter fullscreen mode Exit fullscreen mode

'use strict';

function queryNestedArray() {
var movieLists = [{
name: "New Releases",
videos: [{
"id": 70111470,
"title": "Die Hard",
"rating": 4.0
}, {
"id": 654356453,
"title": "Bad Boys",
"rating": 5.0
}]
}, {
name: "Dramas",
videos: [{
"id": 65432445,
"title": "The Chamber",
"rating": 4.0
}, {
"id": 675465,
"title": "Fracture",
"rating": 5.0
}]
}],
allVideoIdsInMovieLists = [];

movieLists.forEach(function(movieList) {
return movieList.videos.forEach(function(video) {
return allVideoIdsInMovieLists.push(video.id);
});
});

return allVideoIdsInMovieLists;
}

console.log(queryNestedArray()); // [70111470, 654356453, 65432445, 675465]

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay