You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在原始数组中连续匹配切片数组元素并获取原索引

Find Consecutive Slice Elements in Original Array & Get Their Indices

Alright, let's break down how to solve this problem: we need to locate where the slice array appears consecutively in the original array, then grab the corresponding original indices for those elements.

First, let's restate our input clearly:

  • Original array (14 elements):
    [ 0 => "hello", 1 => "i", 2 => "like", 3 => "cats", 4 => "they're", 5 => "cute", 6 => "and", 7 => "cuddly", 8 => "you", 9 => "know", 10 => "well", 11 => "i", 12 => "love", 13 => "cats" ]
    
  • Slice array (6 elements we're checking for consecutive matches):
    [ 0 => "like", 1 => "cats", 2 => "they're", 3 => "cute", 4 => "and", 5 => "cuddly" ]
    

Core Approach

The idea is straightforward:

  1. Check if the slice array is longer than the original array (if so, no match exists).
  2. Iterate through the original array, starting at each position where there's enough remaining elements to fit the slice.
  3. For each starting position, extract a segment of the original array that's the same length as the slice.
  4. Compare this segment to the slice array—if they match exactly, collect the indices from the starting position through to the end of the matched segment.

Example Implementation (PHP)

Here's a concrete PHP solution that finds the first consecutive match (easily adjusted to find all matches):

// Define our arrays
$original = [
    "hello", "i", "like", "cats", "they're", "cute", "and", "cuddly",
    "you", "know", "well", "i", "love", "cats"
];
$slice = ["like", "cats", "they're", "cute", "and", "cuddly"];

$originalLen = count($original);
$sliceLen = count($slice);
$matchingIndices = [];

// Loop through possible starting positions
for ($i = 0; $i <= $originalLen - $sliceLen; $i++) {
    // Extract the segment from original array starting at $i
    $currentSegment = array_slice($original, $i, $sliceLen);
    // Check if the segment matches the slice
    if ($currentSegment === $slice) {
        // Generate the range of indices for this match
        $matchingIndices = range($i, $i + $sliceLen - 1);
        // Break if we only need the first match; remove to find all matches
        break;
    }
}

// Output the result
print_r($matchingIndices);
// Result: Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 [5] => 7 )

Example Implementation (JavaScript)

If you're working with JavaScript, here's an equivalent solution:

const original = ["hello", "i", "like", "cats", "they're", "cute", "and", "cuddly", "you", "know", "well", "i", "love", "cats"];
const slice = ["like", "cats", "they're", "cute", "and", "cuddly"];

const originalLen = original.length;
const sliceLen = slice.length;
let matchingIndices = [];

for (let i = 0; i <= originalLen - sliceLen; i++) {
    const currentSegment = original.slice(i, i + sliceLen);
    // Compare arrays (using JSON.stringify for simplicity—adjust for complex elements)
    if (JSON.stringify(currentSegment) === JSON.stringify(slice)) {
        // Create the index array
        matchingIndices = Array.from({ length: sliceLen }, (_, idx) => i + idx);
        // Break for first match; remove to find all
        break;
    }
}

console.log(matchingIndices);
// Result: [2, 3, 4, 5, 6, 7]

Key Notes

  • Handling multiple matches: If you need to find all consecutive occurrences of the slice array in the original array, just remove the break statement and push each set of matching indices into the result array instead of overwriting it.
  • Complex elements: If your arrays contain objects/non-primitive values, you'll need a custom comparison function instead of === or JSON.stringify to check for matches.

内容的提问来源于stack exchange,提问作者Luka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:09:12