首页 > 解决方案 > Javascript:如何获取数组中特定顺序值的索引?

问题描述

我目前正在尝试创建一个马尔可夫链。现在,我需要获取数组中某些值的索引。有没有可能的方法?

我尝试使用 indexOf,但它只支持一个参数。

假设有一个名为 INDEX 的函数可以满足我的需要。

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

标签: javascriptarrays

解决方案


使用.findIndex, 并检查every数组项之一是否跟随当前索引:

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


推荐阅读