Ali Massoud
Ali Massoud

Reputation: 17

Search function (JAVASCRIPT)

I've an array of strings and a string as an input. What I need to do is get an output of the strings that have letters in the same order as the letters in the input.

input-->output
(d -->[dune,to kill a mockingbird,the sun and her flowers,lord of the flies])
(du -->[dune])
(dune -->[dune])
(t -->[the sun and her flowers,the grapes of wrath,lord of the flies, to kill a mockingbird])
(the -->[the sun and her flowers,the grapes of wrath,lord of the flies])

Here's what I've tried to do (I know its complex ah):-

var input = "du";
var sl = ["dune","to kill a mockingbird","leaves of grass","the sun and her flowers","lord of the flies","the grapes of wrath"];
var slc = [];

if(input.length<=0)
{
  slc.push("No Results Found");
}


for(var i=0; i<input.length; i++)
{
  for(var j=0; j<sl.length;j++)
  {
    for(var z=0; z<sl[j].length; z++)
    {
      if(input.charAt(i)==sl[j].charAt(z))
      {
         slc.push(sl[j]);
      }
    }
  } 
}
 
function removeDups(slc) {
  let unique = {};
  slc.forEach(function(x) {
    if(!unique[x]) {
      unique[x] = true;
    }
  });
  return Object.keys(unique);
}
slx = removeDups(slc);

Upvotes: 0

Views: 57

Answers (2)

James
James

Reputation: 387

If you care about sorting by occurrences, this can help. Otherwise rwusana has a great answer

count = e => (e.match(new RegExp(input, 'g')) || []).length
sl.filter(e => e.includes(input))
  .sort((a, b) => count(b) - count(a))

Upvotes: 0

rwusana
rwusana

Reputation: 137

The 'some string'.includes('substring') method will make the string searching easier. Also see the easy way to keep unique values only.

var input = 'du';
var sl = ["dune", "to kill a mockingbird", "leaves of grass", "the sun and her flowers", "lord of the flies", "the grapes of wrath"];

var slc = sl.filter(str => str.includes(input));

// to make unique
slc = slc.filter((str,i)=>i===slc.indexOf(str));

Upvotes: 1

Related Questions