1

function calWinner(arr) { //winning combination const winningIds = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ] for (let i = 0; i < winningIds.length; i++) { calculate(arr, winningIds[i]) } } function calculate(sup, sub) { sup.sort() sub.sort() let i = 0 let j = 0 for (i, j; i < sup.length && j < sub.length;) { if (sup[i] < sub[j]) { ++i } else if (sup[i] == sub[j]) { ++i, ++j } else { return false } } return j == sub.length; } calWinner([1, 3, 7, 4])

I'm trying to write a function that takes an array, and check if it has every element in a nested array in an object inside of the function.

I've added a function I found from this post, but not sure why i am getting undefined instead of true.

4
  • In the old days of Yore I had been studiyng Pascal, and there there was an excellent relational operator ‘IN’. One could use it to determine whether one array is a subset of another one. If Pascal could do it, modern languages should have similar features too. Commented Feb 12, 2018 at 4:27
  • 1
    @wintermute you are right - using a modern search engine reveals the presence of array.includes in JavaScript Commented Feb 12, 2018 at 4:30
  • your calWinner function is not returning anything! Commented Feb 12, 2018 at 4:36
  • thanks @diogenesgg, i thought it was, as the nested calculate function returns either true or false. could you tell me how calWinner can return something? Commented Feb 12, 2018 at 4:39

1 Answer 1

2

Assuming you want to return true if any array from winningIds is inside arr, this is the code:

function calWinner(arr) { //winning combination const winningIds = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ] var containsWinner = false; for (let i = 0; i < winningIds.length && !containsWinner; i++) { containsWinner = calculate(arr, winningIds[i]) } return containsWinner; } function calculate(sup, sub) { sup.sort() sub.sort() for (var i = 0; i < sub.length; i++) { if (sup.indexOf(sub[i]) == -1) { return false; } } return true; } calWinner([1, 3, 7, 4]); 
Sign up to request clarification or add additional context in comments.

2 Comments

To make it stop at the the first winningId it finds; After checking that [1, 4, 7] is inside arr, containsWinner becomes true, and the loop stops;
thanks so much! totally missed the part that containsWinner was assigned to the result of calculate()!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.