繁体   English   中英

如何使用在Javascript中具有共同值的另一个数组元素的索引获取数组?

[英]How to use get an array of indexes of another array elements that has common values in Javascript?

我有一个对象的数组arr ,每个对象的形式如下:

obj={id: /*some string*/,  //id is unique
     msgDetails: { content: /*some string*/,time : /*number*/ }
     }

为了通过其id值获取特定元素的索引,我使用以下命令:

var idIndex=Babble.messages.findIndex(function(element){
   return element.id===num;
});

有没有一种方法可以获取arr中具有id>=num的元素的所有索引,其中num是给定的数字,而没有for循环?

您可以使用filter代替for

data.filter(d => Number(d.id) > id);

 var data = [{ id: "1", msgDetails: { content: "abc1", time: 1 } },{ id: "2", msgDetails: { content: "abc2", time: 1 } },{ id: "3", msgDetails: { content: "abc3", time: 1 } },{ id: "4", msgDetails: { content: "abc4", time: 1 } }]; var filterData = function(id) { return data.filter(d => Number(d.id) > id); }; console.log(filterData(2)); // Another way var filterId = function(cond) { return data.filter(d => cond(Number(d.id))); }; console.log(filterId(id => id > 2)); 

您可以通过.map().filter()集合来获取所需的索引。

var ids = Babble.messages.map((e, i) => [+e.id, i])
                         .filter(a => a[0] >= num)
                         .map(a => a[1]);

您将首先使用map获取索引,然后对其进行链式filter

 var Babble = { messages: [{ id: "1", msgDetails: { content: "abc", time: 10 }}, { id: "3", msgDetails: { content: "word", time: 15 }}, { id: "5", msgDetails: { content: "phrase", time: 12 }}, { id: "7", msgDetails: { content: "test", time: 21 }}] }; var num = 4; var idIndexes = Babble.messages.map( (el, i) => el.id >= num ? i : null ) .filter(i => i !== null); console.log('indexes with id-values greater or equal than ' + num + ':'); console.log(idIndexes); 

这将记录ID等于或大于指定ID的项目的索引。

 var messages = [ { id: 10 }, { id: 12 }, { id: 2 }, { id: 20 }, { id: 30 } ]; function getIndexesForId(id) { // Create a result array var indexes = []; // Loop over all messages. messages.forEach((item, index) => { // Check if message ID is equal to or larger than requested ID. if (item.id >= id) { // Push the index of the current item into the result array. indexes.push(index); } }); // Return the array. return indexes; } console.log(getIndexesForId(10)); console.log(getIndexesForId(20)); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM