Reputation: 221
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 :
takes 2 parameters:
and returns the indexes of the decomposed string
*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:
the string (userInputText) will only contain words that are listed in the array(animals)
there can be more than one white space (i.e. ' ') in between each word
something like this :
var userInputText = "2 Cats Hippo Grey Dog Lion Hippo Lion 2 Cats Black Widow Spider Hippo Hippo";
Upvotes: 0
Views: 826
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 withindexOf()
, becauseindexOf
returns if found the index0 ... 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