2017-08-28 82 views
0

我有对象的数组arr,每个对象具有以下形式:如何使用获取另一个在Javascript中具有公共值的数组元素的索引数组?

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>=numnum是给定的数字,没有for循环?

+3

退房['filter'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)。 –

+0

@MikeC谢谢! ... – user8244016

回答

2

可以使用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));

2

可以.map().filter()收集得到的指标要。

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

你会首先使用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);

0

这将记录项目的指标与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));

相关问题