Compare a string array with another string array and create a new array

2

I need a method / algorithm found in array1 strings of array2 and create a new array ( array3 ) with all stings separated from array2 .

For example

array1 = ['azxsdfghjkazxfgtfgt'];

The array2 would look like this:

array2 = ['azx', 'sdf', 'ghjk', 'fgt'];

array3 would look like this:

array3 = ['azx','sdf','ghjk', 'azx', 'fgt', 'fgt'];

    
asked by anonymous 18.10.2017 / 17:19

1 answer

1

You can go through this string and cut the beginning by checking if this substring starts with any of the pieces that array2 has.

Example:

const array1 = ['azxsdfghjkazxfgtfgt'];
const array2 = ['azx', 'sdf', 'ghjk', 'fgt'];

function extrair(string, arr) {
  var encontradas = [];
  for (var i = 0; i < string.length; i++) {
    arr.forEach(function(match) {
      if (string.slice(i).indexOf(match) == 0) encontradas.push(match);
    });
  }
  return encontradas;
}

var array3 = extrair(array1[0], array2);
console.log(array3); // ['azx','sdf','ghjk', 'azx', 'fgt', 'fgt'];
    
18.10.2017 / 17:36