[英]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.