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

时间:2017-08-28 20:33:00

标签: 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循环?

4 个答案:

答案 0 :(得分: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));




答案 1 :(得分:2)

您可以MenuControllerMain集合来获取索引。

.map()

答案 2 :(得分: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);




答案 3 :(得分: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));