2

I'm currently trying to create a markov chain. Right now, I need to get the index of some values in an array. Is there any way that is possible?

I tried to use indexOf, but that only supports one argument.

Let's assume there is a function named INDEX that does what I need.

const arr = [1, 2, 3, 4, 3, 2, 3, 1];
INDEX(arr, [1, 2]) // returns 0, because 1, 2 is in the first index in the array.
INDEX(arr, [3, 4, 3]) // returns 2, because 3, 4, 3 starts at the third index.
INDEX(arr, [2, 3]) // returns 1, because there are two 2, 3s, so it returns the first.
INDEX(arr, [5, 6]) // returns -1, because it is not in the array.
INDEX(arr, [1, 4]) // even though these values are in the array, they aren't in the order, so returns -1
3
  • how large can your array be? Commented Oct 9, 2019 at 4:54
  • Could you treat it like a string and use substr? Commented Oct 9, 2019 at 4:55
  • @pavanskipo Around 2 - 12 in length. Commented Oct 9, 2019 at 4:57

2 Answers 2

5

Use .findIndex, and check whether every one of the array items follows the current index:

const arr = [1, 2, 3, 4, 3, 2, 3, 1];

const INDEX = (arr, toFind) => arr.findIndex(
  (_, baseI, arr) => toFind.every((item, i) => arr[baseI + i] === item)
);

console.log(
  INDEX(arr, [1, 2]), // returns 0, because 1, 2 is in the first index in the array.
  INDEX(arr, [3, 4, 3]), // returns 2, because 3, 4, 3 starts at the third index.
  INDEX(arr, [2, 3]), // returns 1, because there are two 2, 3s, so it returns the first.
  INDEX(arr, [5, 6]), // returns -1, because it is not in the array.
  INDEX(arr, [1, 4]) // even though these values are in the array, they aren't in the order, so returns -1
);

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

2 Comments

Thank you! This was what I needed! My life purpose is fulfilled now.
@WilliamWill Please accept the answer.. if it works for you
1

A very simple and neat approach is to deal with strings in this case.

So you can convert both the arrays to strings and use String.prototype.indexOf()

const INDEX = (arr, toFind) => arr.join('').indexOf(toFind.join(''))

const arr = [1, 2, 3, 4, 3, 2, 3, 1]

const INDEX = (arr, toFind) => arr.join('').indexOf(toFind.join(''))

console.log(
  INDEX(arr, [1, 2]),
  INDEX(arr, [3, 4, 3]),
  INDEX(arr, [2, 3]),
  INDEX(arr, [5, 6]),
  INDEX(arr, [1, 4])
)

1 Comment

This will not be reliable if the array items are outside the single digits, or if they're decimal, or if they're non-numbers

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.