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

7
  • You can join 2 array and use parent.indexOf(child) > -1 Commented Apr 7, 2018 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 Commented Apr 7, 2018 at 11:33
  • 2
    You're asking us to di the work for you... What have you tried so far? Commented Apr 7, 2018 at 11:34
  • I have tried this stackoverflow.com/questions/41661287/…. It didn't work Commented Apr 7, 2018 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"]? Commented Apr 7, 2018 at 11:47

5 Answers 5

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);

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

1 Comment

The first approach doesn’t work for repeating elements. The second approach doesn’t work for elements that contain commas.
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);

2 Comments

Instead of using JSON.stringify() and then replace the "array" part... use .join()
@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.
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));

Comments

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);

2 Comments

If you want more good performance, see details like strstr of c, see stackoverflow.com/questions/12784766/…
This doesn’t work. [ "abc" ] isn’t a subarray of [ "a", "b", "c", "d" ].
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")
}

3 Comments

This will fail sometimes.
In which case,?
If I remember my JavaScript correctly, parent = ["a,b", "c"]; child = ["a", "b", "c"]; ought to do it.

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.