samedi 30 avril 2016

Javascript - Search for whole words inside an array and create new array with coincidences

Having an array of arrays named data with following format:

> data[1].toString()
"Seed Keywords,disconnectors,EUR,210,0.03,,,,,N,Y," 

And another array named groupKeywordsText with a list of words to find inside the array data:

> console.log(groupKeywordsText);
["switch", "ac", "high", "switches", "disconnect", "voltage", "isolator"]

I need to create a set of new arrays that include only elements from data which contains a whole word from groupKeywordsText.

SOME EXAMPLES:

An array can be assigned in only one of the new arrays:

> data[3].toString()
"Keyword Ideas,ac,EUR,1900,0.00,1.58,,,,N,N,"

  • Will be assigned to the second new array, because "ac" is exactly one of the searched term.

An array can be assigned in multiple new arrays:

> data[12].toString()
"Keyword Ideas,high voltage,EUR,27100,0.00,1.58,,,,N,N,"

  • Will be assigned to the third new array, because "high side" contains the term to search: "high".
  • Additionally, it will be included in the 5th array, as "voltage" also appears.

An array can be assigned in multiple new arrays, but not in others:

> data[18].toString()
"Keyword Ideas,isolator for switch,EUR,1100,0.00,1.58,,,,N,N,"

  • Will be assigned to the first new array, because "isolator for switch" contains the term to search: "switch".
  • Additionally, it will be included in the 6th array, as "isolator" also appears.
  • However, it will not appear in the 4th array ("switches"), because we search for, and only exactly for, "switch".

An array cannot be assigned in new arrays:

> data[28].toString()
"Keyword Ideas,stackoverflow,EUR,1900,0.00,1.58,,,,N,N,"

  • Wont be assigned to a new array, because "stackoverflow" isn't a searched term.

So far, my code looks like:

    for ( var i = 0, l = groupKeywordsText.length; i < l; i++ ) {

        keywordToSearch = groupKeywordsText[i];
        var length = data.length;
        this["keywordGroup"+i] = [];

                for(var j = 0; j < length; j++) {
                    if (data[j][1] == keywordToSearch) {
                    this["keywordGroup"+i].push(data[j][1]);
                    }
                }

        console.log(this["keywordGroup"+i]);
    }

How can I search for whole (not partial) words inside a string?

Aucun commentaire:

Enregistrer un commentaire