亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

獲取數組對象中的連續元素

獲取數組對象中的連續元素

白衣染霜花 2023-09-28 16:02:14
示例:我有一個對象數組: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}]謝謝大家
查看完整描述

1 回答

?
胡說叔叔

TA貢獻1804條經驗 獲得超8個贊

這是一個時間復雜度為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 array

const result = [];


// current index of the test

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


查看完整回答
反對 回復 2023-09-28
  • 1 回答
  • 0 關注
  • 138 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號