获取数组对象中的连续元素

示例:我有一个对象数组:


a= [

{description: 'H', order: 1},


{description: 'K', order: 2},


{description: 'K', order: 3},


{description: 'H', order: 4}, //I want choose this


{description: 'e', order: 5}, //I want choose this


{description: 'l', order: 6}, //I want choose this


{description: 'l', order: 7}, //I want choose this


{description: 'o', order: 8}, //I want choose this


{description: 'e', order: 9},


{description: 'l', order: 10}


]

我想依次过滤并找到 5 个对象元素(它们按给定数组中的顺序/顺序出现),我的期望是:


b = [


{description: 'H', order: 4},


{description: 'e', order: 5}, 


{description: 'l', order: 6},


{description: 'l', order: 7},


{description: 'o', order: 8}

]

谢谢大家


白衣染霜花
浏览 106回答 1
1回答

胡说叔叔

这是一个时间复杂度为O(n)const arr = [    { description: 'H', order: 1 },    { description: 'K', order: 2 },    { description: 'K', order: 3 },    { description: 'H', order: 4 },    { description: 'e', order: 5 },    { description: 'l', order: 6 },    { description: 'l', order: 7 },    { description: 'o', order: 8 },    { description: 'e', order: 9 },    { description: 'l', order: 10 }];const key = 'Hello';// result arrayconst result = [];// current index of the testlet index = 0;for (let e of arr) {    // if matches the test, add the element to the result array and increse the index    if (e.description === key[index]) {        result.push(e);        index++;                // if already found the result, stop the iteration        if (index >= key.length) break;    } else {  // if failed the test, clear the index and the result        index = 0;        result.length = 0;    }}console.log(result);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript