Ben
Ben

Reputation: 5361

Combine array items from different properties in a JavaScript object

I'm trying create a function that will iterate an object of arrays, and return one array that concatenates each element from one array to each element in the other arrays:

Object like so:

kitchen = {
    food: [".bacon",".bananas"],
    drinks: [".soda",".beer"],
    apps: ['.fritters','.wings']
}

Desired returned array:

[
 ".bacon.soda",".bacon.beer",
 ".bananas.soda",".bananas.beer",
 ".bacon.fritters",".bacon.wings",
 ".bananas.fritters",".bananas.wings", 
 ".soda.fritters",".soda.wings",
 ".beer.fritters",".beer.wings"
]

I'm having difficulty wrapping my brain around how to accomplish this. One thought I had was to create another object and create a hash where each array item becomes a property and then looping through so I have something like:

newObj = {
    ".bacon": [".soda",".beer",".fritters",".wings"]
    ".bananas": [".soda",".beer"...etc]
    etc...
}

then loop through each prop, concatenating the property on each array element into a new array? Not sure if that's overkill though?

Plain JS is fine, but if you have a coffeescript solution as well that would be great too.

Thanks

Upvotes: 2

Views: 149

Answers (2)

alexpods
alexpods

Reputation: 48505

Try this:

var result = [];
var keys = Object.keys(kitchen);

for (var i = 0; i < keys.length; i++) {

    kitchen[keys[i]].forEach(function(ingred1) {
        for (var j = i+1; j < keys.length; j++) {

            kitchen[keys[j]].forEach(function(ingred2) {
                result.push(ingred1 + ingred2);
            });
        }
    });
}

console.log(result);

Upvotes: 1

JLRishe
JLRishe

Reputation: 101680

Here's a solution that makes use of CoffeeScript syntax (since you asked for a CoffeeScript answer and then deleted that request?):

kitchen = 
    food: [".bacon",".bananas"]
    drinks: [".soda",".beer"]
    apps: ['.fritters','.wings']

allGroups = Object.keys(kitchen).map (key) -> kitchen[key]

allValues = []
allGroups.forEach (group, i) ->
    otherValues = Array.prototype.concat.apply [], allGroups.slice(i + 1)
    group.forEach (v1) -> otherValues.forEach (v2) -> allValues.push(v1 + v2)

console.log(allValues)

Here is the plain JS version:

var kitchen = {
  food: [".bacon", ".bananas"],
  drinks: [".soda", ".beer"],
  apps: ['.fritters', '.wings']
}

var allGroups = Object.keys(kitchen).map(function(key) {
  return kitchen[key];
});

var allValues = []
allGroups.forEach(function(group, i) {
  var otherValues = Array.prototype.concat.apply([], allGroups.slice(i + 1));
  group.forEach(function(v1) {
    otherValues.forEach(function(v2) {
      allValues.push(v1 + v2);
    });
  });
});

console.log(allValues)

Upvotes: 1

Related Questions