3

Suppose I have arrays parent and child. I want to check if a child exists inside a parent array. The ordering matters.
Example:

parent = ["x", "a", "b", "c", "d", "e", "f", "g"]
child = ["a", "b", "c"]
//returns true

Example:
When parent has a different order:

parent = ["x", "g", "b", "c", "d", "e", "f", "a"]
child = ["a", "b", "c"]
//It should return false   

How would I achieve this in Javascript?
Edit: I have tried this How to check if an array contains another array? but it did not work for my case

J Duh
  • 161
  • 1
  • 11
  • You can `join` 2 array and use parent.`indexOf`(child) > -1 – Tan Duong Apr 07 '18 at 11:33
  • 2
    before asking how to do something on stackoverflow, please tell us what you have already tried. We are not a code writing service, you have to try something, and then ask for help – Pierre Apr 07 '18 at 11:33
  • 2
    You're asking us to di the work for you... What have you tried so far? – NielsNet Apr 07 '18 at 11:34
  • I have tried this https://stackoverflow.com/questions/41661287/how-to-check-if-an-array-contains-another-array. It didn't work – J Duh Apr 07 '18 at 11:35
  • @JDuh That’s not the same situation at all. You’re searching for sub-arrays, not for array elements that are arrays. Do you also need to check whether the items in the “child” array follow one another in the “parent” array? I.e. is `["a", "b", "x", "c"]` a valid “parent” for `["a", "b", "c"]`? – Sebastian Simon Apr 07 '18 at 11:47
  • @Tan nope, that's not really right. Consider https://jsfiddle.net/x1f6x6jn/ (logs "found"). – nicael Apr 07 '18 at 13:14
  • @JDuh You can tick the answer if it was really helpful to you :) – Ankit Agarwal Aug 11 '18 at 05:59

5 Answers5

2

You can run a loop for child and change the index accordingly. You can also use a match variable to detect change in the sequence.

RETURN TRUE

var parent = ["x", "a", "b", "c", "d", "e", "f", "g"]
var child = ["a", "b", "c"];

var initIndex = parent.indexOf(child[0]);
var match = true;
for(var i=1; i<child.length; i++){
  var varIndex = parent.indexOf(child[i]);
  if( varIndex === initIndex+1){
    initIndex = varIndex;
    continue;
  }
  match = false;
}

console.log(match);

RETURN FALSE

var parent = ["x", "g", "b", "c", "d", "e", "f", "a"]
var child = ["a", "b", "c"];

var initIndex = parent.indexOf(child[0]);
var match = true;
for(var i=1; i<child.length; i++){
  var varIndex = parent.indexOf(child[i]);
  if( varIndex === initIndex+1){
    initIndex = varIndex;
    continue;
  }
  match = false;
}

//return false
console.log(match);

USING STRING OPERATION

You can also convert the array to string to avoid those loop:

var parent = ["x", "g", "b", "c", "d", "e", "f", "a"]
var child = ["a", "b", "c"]

var parentStr = parent.toString();
var match = parentStr.indexOf(child.toString()) !== -1;
//return false
console.log(match);

parent = ["x", "a", "b", "c", "d", "e", "f", "g"]
child = ["a", "b", "c"]

parentStr = parent.toString();
match = parentStr.indexOf(child.toString()) !== -1;
//return true
console.log(match);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
1

Convert the array to string by using JSON.stringify() and remove the square brackets from child string.

Now check the indexOf child in parent to check if it contains the child.

let parent = ["x", "a", "b", "c", "d", "e", "f", "g"];
let child = ["a", "b", "c"];
var parStr = JSON.stringify(parent);
var chldStr = JSON.stringify(child).replace('[', '').replace(']', '')

console.log(parStr.indexOf(chldStr) !== -1);
Sankar
  • 6,908
  • 2
  • 30
  • 53
  • Instead of using `JSON.stringify()` and then replace the "array" part... use `.join()` – Andreas Apr 07 '18 at 11:48
  • @Andreas No. This will fail if the array elements contain commas. The JSON approach is more robust as it guarantees valid JSON delimiters and quote escaping. – Sebastian Simon Oct 15 '22 at 14:33
1

I wrote a function for this a while back that takes some paramenters:

Array.prototype.containsArray = function (child, orderSensitivity, caseSensitivity, typeSensitivity) {
    var self = this;
    if (orderSensitivity) return orderSensitiveComparer();
    else return orderInsensitiveComparer();

    function orderSensitiveComparer() {
        var resultArry = [],
            placeholder = 0;
        if (child.length > self.length) return false;
        for (var i = 0; i < child.length; i++) {
            for (var k = placeholder; k < self.length; k++) {
                if (equalityComparer(self[k], child[i])) {
                    resultArry.push(true);
                    if (resultArry.length === child.length) return true;
                    placeholder = k + 1;
                    break;
                }
                else resultArry = [];
            }
        }
        return false;
    }
    function orderInsensitiveComparer() {
        for (var i = 0; i < child.length; i++) {
            var childHasParentElement = false;
            for (var k = 0; k < self.length; k++) {
                if (equalityComparer(child[i], self[k])) {
                    childHasParentElement = true;
                    break;
                }
            }
            if (!childHasParentElement) return false;
        }
        return true;
    }
    function equalityComparer(a, b) {

        if (caseSensitivity && typeSensitivity) return caseSensitiveEq(a, b) && typeSensitiveEq(a, b);
        else if (!caseSensitivity && typeSensitivity) return caseInsensitiveEq(a, b) && typeSensitiveEq(a, b);
        else if (caseSensitivity && !typeSensitivity) return caseSensitiveEq(a, b) && typeInsensitiveEq(a, b);
        else if (!caseSensitivity && !typeSensitivity) return caseInsensitiveEq(a, b) && typeInsensitiveEq(a, b);
        else throw "Unknown set of parameters";


        function caseSensitiveEq(a, b) {
            return a == b;
        }
        function caseInsensitiveEq(a, b) {
            return (a + "").toLowerCase() == (b + "").toLowerCase();
        }
        function typeSensitiveEq(a, b) {
            return typeof(a) === typeof(b);
        }
        function typeInsensitiveEq(a, b) {
            return true;
        }
    }
}

var parent = [1, 2, 3, "a", "b", "c"];
var child = [1, 2, 3];
var child2 = ["1", "2", "3"];
var child3 = ["A", "b", "C"];
var child4 = ["a", "b", "c"];
var child5 = ["c", "b", "a"];


// Tests:
console.log(parent.containsArray(parent));
console.log(parent.containsArray(child));
console.log(parent.containsArray(child2));

// parent to child 2, order sensitive, not case, not type. => true.
console.log(parent.containsArray(child2, true, false, false));

// parent to child 2, order, not case, type. => false. b/c of type.
console.log(parent.containsArray(child2, true, false, true));

// parent to child 3, order, not case, type. => true.
console.log(parent.containsArray(child3, true, false, true));

// parent to child 4, order, case and type => true.
console.log(parent.containsArray(child4, true, true, true));

// parent to child 4, not order, case and type. => true.
console.log(parent.containsArray(child4, false, true, true));

// parent to child 5, not order case or type => true.
console.log(parent.containsArray(child5));
S. Walker
  • 2,129
  • 12
  • 30
0

var parent = ["x", "g", "b", "c", "d", "e", "f", "a"]
var child = ["a", "b", "c"]

if(parent.join("").search(child.join("")) === -1) {
    console.log("Not found");
} else {
    console.log("found")
}
Ben Rivers
  • 129
  • 10
Sagar Jajoriya
  • 2,377
  • 1
  • 9
  • 17
0

I have a simple method for small sized arrays of this problem.

  1. First join the array to a string, see Array/join
  2. Search substring, see String/indexOf

parent = ["x", "a", "b", "c", "d", "e", "f", "g"];
child = ["a", "b", "c"];
function matchSubArray(parent, child) {
    parentStr = parent.join('');
    childStr = child.join('');
    return parentStr.indexOf(childStr) != -1;
}
matchSubArray(parent, child);
Donghua Liu
  • 1,776
  • 2
  • 21
  • 30