1

Call this array 1:

["one","two","three","four","five"]

I have a second array, array 2, which is a sub-set of array 1. It might look like this:

["one","two"]

I now want to check whether the elements of array 2 are in the same order as the elements in array 1. It doesn't matter how many elements there are in array 2, however they need to be in the same order.

So for example:

["one","two"] ==> true
["two","three"] ==> true
["one","three"] ==> false
["two","one"] ==> false

I believe I have solved this, but I am wondering whether there isn't a better solution or way to approach it, and of course I'm wondering whether there are maybe hidden assumptions I shouldn't have made or errors I have committed. My solution looks like this:

let arr = ["s1","s2","s3","s4","s5","s6"];
let subArray = ["s4","s5"];

let counter = 0;

for(let i=0;i<=arr.length;i++) {
  if(arr[i] === subArray[counter]) {
    counter++;
  } else if(counter>0) {
    counter=0;
  }
  if(counter === subArray.length) {
    console.log('consecutive');
    return true;
  }
}
if(counter !== subArray.length) {
  console.log('not consecutive i guess');
  return false;
}
R. Kohlisch
  • 2,823
  • 6
  • 29
  • 59
  • 1
    Would you not be able to stringify both arrays and do a pregmatch? – Hugo Cox Jul 12 '18 at 22:09
  • both arrays will contain mongodb ids in the end. (I don't know what the answer to your question is, but if it works with mongodb ids, then the answer is probably yes) – R. Kohlisch Jul 12 '18 at 22:10
  • 2
    I would do a pregmatch then to check if the subarray is in the array. – Hugo Cox Jul 12 '18 at 22:14
  • https://stackoverflow.com/questions/1789945/how-to-check-whether-a-string-contains-a-substring-in-javascript – Hugo Cox Jul 12 '18 at 22:38

2 Answers2

4

Use Array.findIndex() to find the index (startIndex) in the containing array of the 1st element in the sub array. Then iterate the the sub array with Array.every(), and check that starting from the startIndex, the sub array's items have an equivalent in the containing array:

const isContained = (arr1, arr2) => {
  const startIndex = arr1.findIndex((item) => item === arr2[0]);
  
  if(startIndex === -1) return false;
  
  return arr2.every((item, i) => item === arr1[i + startIndex]);
}

console.log(isContained(["s1","s2","s3","s4","s5","s6"], ["s4","s5"])); // true

console.log(isContained(["s1","s2","s3","s4","s5","s6"], ["s6","s5"])); // false
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
4

You could do something sneaky like joining both of the array elements and then seeing if the test array's elements joined is a substring of the original array's elements joined.

Ex:

function containsElementsInSameOrder(arr, elements) {
    return arr.join(' ').indexOf(elements.join(' ')) > -1;
}
Ethan Mott
  • 187
  • 4
  • Apart from problems with strings containing ' ' doesn't this fail if you look for ["one","tw"] - since that is a substring of "one two three"? – Hans Olsson Jul 13 '18 at 11:51