常常会有这样一个场景,检查某个list里面有没有某个元素,如果没有则添加进去。那么我们就可以用lodash里面的_.findIndex()了
//append patt to array if not in array.
function findItem (obj, item) {
var findIndex = _.findIndex(obj, function (d) {
return d.toLowerCase() == item.toLowerCase();
});
return findIndex;
}
//Example 0:
//Array find.
var findIndex = test_phase.indexOf(p.promotion_step);
if(findIndex >= 0) {console.log(88888888)}
//Example 1:
var patt = "target_patt";
var test_phase = [];
var findIndex = _.findIndex(test_phase, function (a) {
return a == patt ;})
if (findIndex < 0) {test_phase.push(patt);}
//Example 2:
var foundIdx = _.findIndex(node,{name: d.test_hierarchy});
var node = [];
var nextnode = null;
if (foundIdx < 0) {
//console.log("-----no found")
nextnode = {name:d.test_hierarchy,data:[{buildid: d.buildid, result: d.result}], tmpleaf:tmpleaf };
node.push(nextnode);
}
//Example 3:
results = _.filter(results, function (d) {
return (!(d.removed && d.removed == true)); //will not filter item with d.removed == true.
// return (d.removed && d.removed == true);
});
var results = _.sortBy(results, function (item) {
return -(item.opentime);// reversed by opentime
});
需要在某个list里面过滤符合条件的数据,可用filter()
//Example 1
day_tests = _.filter(day_tests,function(d){
var mm = stage.toLowerCase();
return (new RegExp("^" + mm + ";")).test(d.test_hierarchy.toLowerCase());
// d.test_hierarchy.replace(/;*/,'').toLowerCase()==mm;
//有时候用==在filter里面不起作用。
});
//Example 2
//filter data which contains str_day
var str_day = tmp_day.format("YYYY/MM/DD");
var day_builds = _.filter(obj, function (d) {
return str_day == moment(d.buildend * 1000).format("YYYY/MM/DD");
});
day_builds = _.groupBy(day_builds, function (d) { return d.product; });