Skip to content

Instantly share code, notes, and snippets.

@bbagdad
Created April 26, 2018 08:56
Show Gist options
  • Save bbagdad/212e1c6aa7bdf3ea56267bf03f745c9e to your computer and use it in GitHub Desktop.
Save bbagdad/212e1c6aa7bdf3ea56267bf03f745c9e to your computer and use it in GitHub Desktop.
JavaScript manMany, Projects each element of a sequence to an Array and flattens the resulting sequences into one sequence.
// Projects each element of a sequence to an Array and flattens the resulting sequences into one sequence.
if (!Array.prototype.mapMany) {
Object.defineProperty(Array.prototype, 'mapMany', {
value: function (callback) {
if (this === null) {
throw new TypeError('Array.prototype.mapMany ' +
'called on null or undefined');
}
if (typeof callback !== 'function') {
throw new TypeError(callback +
' is not a function');
}
// 1. Let O be ? ToObject(this value).
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// Steps 3, 4, 5, 6, 7
var k = 0;
// Start with empty array
var value = [];
// 8. Repeat, while k < len
while (k < len) {
// if k exists in o
if (k in o) {
value = value.concat(callback(o[k], k, o))
}
// d. Increase k by 1.
k++;
}
// 9. Return accumulator.
return value;
}
});
}
@bbagdad
Copy link
Author

bbagdad commented Apr 26, 2018

Usage Example:

	var arr = [
		{"id": 1, "Contacts": [{"id": 1},{"id": 2},{"id": 3},{"id": 4}]}, 
		{"id": 2, "Contacts": [{"id": 1},{"id": 2},{"id": 3},{"id": 4}]},
		{"id": 3, "Contacts": [{"id": 1},{"id": 2},{"id": 3}]},
		{"id": 4, "Contacts": [{"id": 1},{"id": 2},{"id": 3}]},
		{"id": 5, "Contacts": [{"id": 1},{"id": 2},{"id": 3},{"id": 4}]}
	];

	arr.mapMany(m => m.Contacts.map(n => n.id));

Result:

	[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 1, 2, 3, 1, 2, 3, 4]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment