Home > Software engineering >  How to return a sorted array of the elements of an array, but only if they are substrings of another
How to return a sorted array of the elements of an array, but only if they are substrings of another

Time:01-05

This is a Kata exercise from codewars.com:

"""Given two arrays of strings a1 and a2 return a sorted array r in lexicographical order of the strings of a1 which are substrings of strings of a2.

Example 1:

a1 = ["arp", "live", "strong"] a2 = ["lively", "alive", "harp", "sharp", "armstrong"]

returns ["arp", "live", "strong"]

Example 2:

a1 = ["tarp", "mice", "bull"] a2 = ["lively", "alive", "harp", "sharp", "armstrong"]

returns []"""

This is my code so far (I guess something does not work with line 4 ("if (a2.includes(a1[i]))"):

function inArray(a1,a2){
  let r =[];
  for (let i =0; i> a1.length; i  ){
    if (a2.includes(a1[i])){
      r.push(a1[i])
    }
  }
  r = r.sort()
  return r
}

CodePudding user response:

You can use the filter() method to filter the elements of the array to only include those that are substrings of the other array, and then use the sort() method to sort the resulting array. Here's an example of how you could do this:

function sortSubstrings(arr, substrArr) {
  // Use filter() to get only the elements of arr that are substrings of substrArr
  const filteredArr = arr.filter(element => substrArr.includes(element));

  // Use sort() to sort the filtered array
  return filteredArr.sort();
}

Here's an example of how you could use this function:

const arr = ['foo', 'bar', 'baz', 'qux'];
const substrArr = ['foobar', 'quxquux', 'baz'];

const sortedSubstrings = sortSubstrings(arr, substrArr);
console.log(sortedSubstrings); // ['baz', 'foo']

This will return a sorted array of the elements of arr that are substrings of substrArr.

CodePudding user response:

You need to check for substrings of the second array.

This solution features array methods

  • Array#filter for getting a subset of the given array,
  • Array#some, for a check if some (literately) item match a condition,
  • Array#sort for sorting by string or with a callback for a custom sorting.

Beside this, it takes String#includes, which checks if a string is included in another string. This method is available for arrays to check if an item exists (Array#includes), too.

The function is an arrow function, which allows a short design without having (it could as well) a function body and returns the result without a return statement. If you take the function body, it needs a return statement, ir required.

const
    inArray = (array1, array2) => a
        .filter(word => array2.some(checkword => checkword.includes(word)))
        .sort();


console.log(inArray(["arp", "live", "strong"], ["lively", "alive", "harp", "sharp", "armstrong"])); // ["arp", "live", "strong"]
console.log(inArray(["tarp", "mice", "bull"], ["lively", "alive", "harp", "sharp", "armstrong"])); // []

  • Related