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

Asked

Viewed 97 times

2

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

For example

array1 = ['azxsdfghjkazxfgtfgt'];

To array2 would look that way:

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

Already the array3 would look that way:

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

  • I don’t get it... you want to find array1 array2 strings and add them to array2, that’s it?

  • want to find array1 array2 strings and create a new array with all Stings separated from array2

  • And when a piece is found it can be used for future match? or is removed from the algorithm?

  • when the piece is found, it has q be used for match, without removing anything from the algorithm

  • My question is if letters from this previous match can be used if they match with others?

  • this, it can be used with other

Show 1 more comment

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'];

  • 1

    The guy was the result that I wanted, thank you very much, in this function has method that I will still study, but only by this code it will serve as a basis for testing both for these methods that this part of the function as for others, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.