GregorII
GregorII

Reputation: 221

Extracting Index from an Array, that contains each word in the string

Sorry if the title is a bit misleading and inaccurate, but ... didnt know how else to title the problem. So here is it(the Problem) described in details.

How do I create a function that :

*an element in this array can contain/have more then one word in it (i.e. "Grey Dog")

let me show you what I mean by showing the string, the array and the desired output:

var animals = [
"Grey Dog",           //0
"Lion",               //1
"2 Cats",             //2
"Black Widow Spider", //3
"Hippo",              //4
"Bird"                //5
]

var userInputText = "2 Cats Hippo Grey Dog Lion Hippo Lion 2 Cats Black Widow Spider Hippo Hippo";


var output = decomposeStringToIndexes(animals ,userInputText);

and when I trace / log / check the output variable, it will contain:

output = [
2,//2 Cats
4,//Hippo
0,//Grey Dog
1,//Lion
4,//Hippo
1,//Lion
2,//2 Cats
3,//Black Widow Spider
4,//Hippo
4//Hippo
];

EDIT:

something like this :

var userInputText = "2 Cats      Hippo    Grey Dog    Lion   Hippo     Lion 2 Cats Black Widow Spider       Hippo  Hippo";

Upvotes: 0

Views: 826

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386600

I suggest to iterate over the search words and remember the position and build an object with these items. Later strip the indices and return just an array.

~ is a bitwise not operator. It is perfect for use with indexOf(), because indexOf returns if found the index 0 ... n and if not -1:

value  ~value   boolean
 -1  =>   0  =>  false
  0  =>  -1  =>  true
  1  =>  -2  =>  true
  2  =>  -3  =>  true
  and so on 

function decomposeStringToIndexes(array, string) {
    var found = {};
    array.forEach(function (a, i) {
        var p = 0,
            pos = string.indexOf(a);
        while (~pos) { // equal to pos !== -1
            found[pos] = i;
            p = pos + a.length;
            pos = string.indexOf(a, p);
        }
    });
    return Object.keys(found)
        .map(Number)
        .sort(function (a, b) { return a - b; })
        .map(function (k) { return found[k]; });
};

var animals = ["Grey Dog", "Lion", "2 Cats", "Black Widow Spider", "Hippo", "Bird"],
    userInputText = "2 Cats Hippo Grey Dog Lion Hippo Lion 2 Cats Black Widow Spider Hippo Hippo",
    output = decomposeStringToIndexes(animals, userInputText);

document.write('<pre>' + JSON.stringify(output, 0, 4) + '</pre>');

Upvotes: 2

Related Questions