0

I have the following array:

var Set = ("BENELUX,Luxembourg,PP3a,Western_Europe,France,PP6a").split(',');

Working sequentially, I'd like to take 3 elements at a time and assign each to a variable. The result I'd like is:

var Aggreg = ["BENELUX", "Western Europe"]
var Country = ["Luxembourg", "France"] 
var Product = ["PP3a", "PP6a"]

The order of elements in 'Set' will always be sequential and will always be a multiple of 3. I'm sure there's a clever, efficient way to do this. Anyone able to point me in the right direction?

5
  • Do you want the variables to contain a string or an array? Commented Sep 29, 2017 at 16:09
  • I need them to be arrays Commented Sep 29, 2017 at 16:10
  • The expected result is more than three elements at a time Commented Sep 29, 2017 at 16:11
  • And do you want a single string in the arrays, like ["BENELUX, Western Europe"], or do you want each element as it's own string, like ["BENELUX", "Western Europe"]? Commented Sep 29, 2017 at 16:13
  • @Silverburch Check to see if my answer gives the output you're looking for. Commented Sep 29, 2017 at 16:20

4 Answers 4

2

You can use destructuring assignment, increment variables to reflect indexes

var set = "BENELUX,Luxembourg,PP3a,Western_Europe,France,PP6a".split(",");

var n = 0, m = 3;

var fn = (arr, a = 0, b = 3) => [arr[a], arr[b]];

var [Aggreg, Country, Product] = [
  fn(set),
  fn(set, ++n, ++m),
  fn(set, ++n, ++m)
];

console.log(Aggreg, Country, Product);

alternatively

var set = "BENELUX,Luxembourg,PP3a,Western_Europe,France,PP6a".split(",");

var fn = function* (arr) {
  var n = 0, m = 3;
  while (m < arr.length) {
    yield [arr[n], arr[m]];
    n += 1; m += 1;
  }
};

var [Aggreg, Country, Product] = fn(set);

console.log(Aggreg, Country, Product);

Sign up to request clarification or add additional context in comments.

5 Comments

re check the desired output. Aggreg should be every 3n, Country every 3n+1 and Product every 3n+2
"Set will always be a multiple of 3" implies to me that it can have 3n number of elements, this solution only handles 6 elements
@mhodges Not following what you mean?
This doesn't handle more than 6 elements in Set
@mhodges How so?
1

You can use .reduce() to get each part into an array inside a single object, and then use a destructuring assignment to assign individual variables, like so:

var Set = ("BENELUX,Luxembourg,PP3a,Western_Europe,France,PP6a").split(',');

var {Aggreg, Country, Product} = Set.reduce(function (result, curr, index) {
  if (index % 3 === 0) {
    result.Aggreg.push(curr);
  }
  else if (index % 3 === 1) {
    result.Country.push(curr);
  }
  else {
    result.Product.push(curr);
  }
  return result;
}, {Aggreg: [], Country: [], Product: []})

console.log(Aggreg);
console.log(Country);
console.log(Product);

5 Comments

A bit too complicated IMO
@soywod It does the exact same thing yours does, just with 1 iteration of the array, rather than 3. Reduce is a pretty common looping structure in JavaScript - not sure what is complicated here
Why the downvote? (Not my answer, but this answer is correct...)
I don't understand the downvote either. The single iteration of the array is exactly what I need given that 'Set' could potentially be big. Much appreciated.
@Silverburch You're welcome. If you found this answer helpful, be sure to upvote and mark as accepted.
1

Just filter your array using the modulo (if you are sure about your data - in this case, be sure to get a multiple of 3 array size) :

const data = "BENELUX,Luxembourg,PP3a,Western_Europe,France,PP6a".split(",")

function extract(data, shift) {
  return data.filter((value, index) => (index % 3) === shift)
}

const Aggreg = extract(data, 0)
const Country = extract(data, 1)
const Product = extract(data, 2)

console.log(Aggreg, Country, Product)

Comments

1

Could make use of a simple Array.prototype.forEach():

var Set = "BENELUX,Luxembourg,PP3a,Western_Europe,France,PP6a".split(',');

var Aggreg = [],
    Country = [],
    Product = [];


Set.forEach(function(item, index) { //For each item in the array
  switch (index % 3) {              //Get remainder of index/3
    case 0:
      Aggreg.push(item);            //If 0, Aggreg
      break;
    case 1:
      Country.push(item);           //If 1, Country
      break;
    case 2:
      Product.push(item);           //If 2, Product
  }
})

console.log(Aggreg, Country, Product);

3 Comments

A downvote on a correct answer. Welcome to Stack Overflow :)
Not a huge fan of impure functions, but I will upvote for a correct answer and to offset the random downvote. lol
@mhodges Appreciated! I do somewhat regret littering the scope but oh well, I guess it's got readability going for it :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.