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.
Problem
Flatten the movieLists array into an array of video ids
Let’s solve with Array.prototype.forEach()
'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]
Top comments (0)