2

Is there a method with javascript that can return n sequences of string that form a part of a larger string?

For example, in a sequence like:

Paris, Italy, London, Perth, Moscow, Wellington

How could I get n word-pairs where n = 2 in this example. The output would be:

Paris, Italy
London, Perth
Moscow, Wellington

Is there a built in method with Javascript that could help me achieve this?

Amanda
  • 2,013
  • 3
  • 24
  • 57

2 Answers2

2

Use a regular expression that matches non-space characters, followed by a comma and space, followed by more non-space characters (where the next character after the match is a comma or the end of the string):

const input = 'Paris, Italy, London, Perth, Moscow, Wellington';
console.log(
  input.match(/\S+, \S+(?=,|$)/g)
);

For additional sequences of words, repeat the initial non-space characters followed by a comma and space, eg:

const input = 'Paris, Italy, London, Perth, Moscow, Wellington';
console.log(
  input.match(/(?:\S+, ){2}\S+(?=,|$)/g)
);

The above matches 3 words. For 4 words, just change the {2} to {3}, and so on.

If you want a function, pass the number of words you need into new RegExp:

const getPairs = (str, words) => {
  const pattern = new RegExp(String.raw`(?:\S+, ){${words - 1}}\S+(?=,|$)`, 'g');
  return str.match(pattern);
};

const input = 'Paris, Italy, London, Perth, Moscow, Wellington';
console.log(
  getPairs(input, 3)
);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

You could do this by grouping them using a modulo, allowing you to get the relevant size of chunks:

const input = 'Paris, Italy, London, Perth, Moscow, Wellington';

const groupBy = f => arr => arr.reduce((prev, curr, i) => {
  const key = f(curr, i);
  const hasKey = prev.hasOwnProperty(`${key}`);
  
  return {
    ...prev,
    [key]: [...(hasKey ? prev[key] : []), curr]
  }
}, {})

const grouper = size => (_, i) => i % size;

const splitIntoChunks = (chunkSize, arr) => Object.values(groupBy(grouper(arr.length / chunkSize))(arr))

console.dir(splitIntoChunks(2, input.split(', ')))
OliverRadini
  • 6,238
  • 1
  • 21
  • 46