簡體   English   中英

在JavaScript中的數組中搜索子數組

[英]Search for a subarray in an array in JavaScript

我有一個對象數組:

arrObj : [{ id: 0, text: 'At', start: '15.000' },
      { id: 1, text: 'the', start: '15.492'},
      { id: 2, text: 'left', start: '15.984'},
      { id: 3, text: 'we', start: '16.476' },
      { id: 4, text: 'can', start: '16.967'},
      { id: 5, text: 'see...', start: '17.459' },
      { id: 6, text: 'At', start: '18.166'},
      { id: 7, text: 'the', start: '18.440' }]

我必須搜索一個數組並返回開始和結束單詞id。 例如在這種情況下:

["At", "the"]

我必須返回[(0,1),(6,7)]我當前在每個循環中使用a來迭代arrObj並查看單詞是否匹配。 我還通過加入對象文本嘗試了indexOf,但它返回的是char索引而不是數組索引。

但這似乎並不有效。 我如何有效地搜索類似的東西?

您可以使用reduce來獲取數組中的開始和結束位置:

 let arrObj = [{ id: 0, text: 'At', start: '15.000' }, { id: 1, text: 'the', start: '15.492'}, { id: 2, text: 'left', start: '15.984'}, { id: 3, text: 'we', start: '16.476' }, { id: 4, text: 'can', start: '16.967'}, { id: 5, text: 'see...', start: '17.459' }, { id: 6, text: 'At', start: '18.166'}, { id: 7, text: 'the', start: '18.440' }]; let arr = ["At", "the"]; let res = arrObj.reduce((a, b, i) => { let index = arr.indexOf(b.text); if (index === 0) { a.push(i); } else if (index === 1) { a.push([a.pop()].concat(i)); } return a; }, []); console.log(res); 

請注意,這僅在具有搜索詞的數組包含2個條目的情況下起作用。

如果數組中需要兩個以上的搜索詞,則可以使用:

 let arrObj = [{ id: 0, text: 'At', start: '15.000' }, { id: 1, text: 'the', start: '15.492'}, { id: 2, text: 'left', start: '15.984'}, { id: 3, text: 'we', start: '16.476' }, { id: 4, text: 'can', start: '16.967'}, { id: 5, text: 'see...', start: '17.459' }, { id: 6, text: 'At', start: '18.166'}, { id: 7, text: 'the', start: '18.440' }] let arr = ["At", "the", "left"]; let res = arrObj.reduce((a,b,i) => { let index = arr.indexOf(b.text); if (index > -1) { if (index % arr.length === 0) { a.push(i); } else { let tmp = a.pop(); a.push(tmp instanceof Array ? tmp.concat(i) : [tmp].concat(i)); } } return a; }, []); console.log(res); 

任何長度的搜索數組的解決方案。 它存儲搜索數組的索引,並以匹配項遞增。

如果找到搜索數組所有項的索引,則僅添加帶有索引的數組。

 var array = [{ id: 0, text: 'At', start: '15.000' }, { id: 1, text: 'the', start: '15.492' }, { id: 2, text: 'left', start: '15.984' }, { id: 3, text: 'we', start: '16.476' }, { id: 4, text: 'can', start: '16.967' }, { id: 5, text: 'see...', start: '17.459' }, { id: 6, text: 'At', start: '18.166' }, { id: 7, text: 'the', start: '18.440' }], search = ["At", "the"], result = array.reduce(function (i, t) { return function (r, a, j) { if (search[i] === a.text) { t.push(j); i++; if (i === search.length) { r.push(t); t = []; i = 0; }; } return r; }; }(0, []), []); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM