Issue
My problem is a bit difficult to explain (since I do not speak English well). I'm developing an app in Angular.js so we speak about Javascript.
Let's suppose we have 2 arrays like this :
[
[
"Item 1",
"Item 2"
],
[
"Item A",
"Item B",
"Item C"
]
]
What I need to obtain is something like this :
[
"Item 1 Item A",
"Item 1 Item B",
"Item 1 Item C",
"Item 2 Item A",
"Item 2 Item B",
"Item 2 Item C"
]
But I think that the real problem is that we could have more arrays (3, 4, 5...) and the number of items in each one is also changing... The final idea is to have every item concatenated to other ones only once. Does someone have an idea ?
I tried angular.forEach, for loops... but I'm not able to find a solution at this time...
Solution
What you want is a solution like so:
[
["Item 1", "Item 2"],
["Item A", "Item B", "Item C"]
].reduce(function(first, second) {
var result = [];
first.forEach(function(first) {
var str = first + ' ';
second.forEach(function(second) {
result.push(str + second);
});
});
return result;
});
The result:
[
"Item 1 Item A",
"Item 1 Item B",
"Item 1 Item C",
"Item 2 Item A",
"Item 2 Item B",
"Item 2 Item C"
]
Update
With multiple arrays:
[
["Black", "White"],
["Apple", "Orange", "Pear"],
["Fast", "Slow",]
].reduce(function(firstArray, currentArray) {
var result = [];
firstArray.forEach(function(first) {
var str = first + ' ';
currentArray.forEach(function(second) {
result.push(str + second);
});
});
return result;
});
And the result:
[
// Black
"Black Apple Fast",
"Black Apple Slow",
"Black Orange Fast",
"Black Orange Slow",
"Black Pear Fast",
"Black Pear Slow",
// White
"White Apple Fast",
"White Apple Slow",
"White Orange Fast",
"White Orange Slow",
"White Pear Fast",
"White Pear Slow"
]
Answered By - istos
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.