繁体   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