1

I have an array of strings ["samantha", "mike", "john", "sammy", "carla"] and an input value of s.

const input = "s";
let names = ["samantha", "mike", "john", "sammy", "carla"];
let filteredNames = names.filter(name => name.startsWith(input));

This gives me "samantha" and "sammy" as a result.

How can I extract the string that all elements of filteredNames start with? So basically: How can I find out that sam is the matching string for this array?

3
  • 1
    I understand your question. give me some time xD Commented Nov 19, 2017 at 23:08
  • 1
    Are you trying to determine the most left-side matches for every string in filteredNames? e.g. ["hat","hats","ham"] -> ha? Commented Nov 19, 2017 at 23:09
  • @Marty Yes, exactly. I had difficulties describing what I'm looking for but your question brings it to the point. Commented Nov 19, 2017 at 23:11

3 Answers 3

4

You can use reduce() on first element of your result array and then use every() to check if current letter is same in every element with same index.

let names = ["samantha", "sammy"];

var found = true;
var r = names[0].split('').reduce(function(r, e, i) {
  var check = names.every(elem => elem[i] == e);
  check && found ? r += e : found = false;
  return r;
}, '')

console.log(r)

Sign up to request clarification or add additional context in comments.

1 Comment

It works. However I need to dig into your statements to get a better understanding :-)
0

const input = "s"
let names = ["samantha", "mike", "john", "sammy", "carla"]
let fN = names.filter(name => name.startsWith(input))
let result = ""
if(fN.length){
    result = input
    for(let i=1; fN.every(x=>x[i]==fN[0][i]); i++)
        result += fN[0][i]
}
console.log(result)

Comments

0

Not necessarily efficient, but something like:

function findCommonPrefix(array) {
   let prefix = "";
   const smallest = findSmallestString(array);

   while (prefix.length < smallest) {
      let test = prefix + array[0][prefix.length];
      if (!(array.every(item => item.indexOf(test) == 0)))
         return prefix;
      prefix = test;
   }
   return prefix;
}

function findSmallestString(array) {
   if (array.length <= 0)
      return -1;

   let smallest = Number.MAX_SAFE_INTEGER;
   for (let x = 0; x < array.length; x++) {
      const len = array[x].length;
      if (smallest > len)
         smallest = len;
   }
   return smallest;
}

let stuff = ["sammy", "samuel"];
console.info(findCommonPrefix(stuff));

stuff = ["sammy", "samuel", "susan"];
console.info(findCommonPrefix(stuff));

stuff = ["sammy", "samuel", "susan", "joe"];
console.info(findCommonPrefix(stuff));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.