【问题标题】:return truthy value from Array.some or _.some从 Array.some 或 _.some 返回真值
【发布时间】:2016-11-24 20:23:40
【问题描述】:

我想从数组中返回真值。一些而不是“真”,

我正在使用

var category;
arduair.aqi_ranges[pollutant].some((item,index)=>  {
  var min =item.range[0];
  var max =item.range[1];
  if (_.inRange(c,min,max)){
    category = index;
    return true;
  }
  return false;
});

但是是一个很丑陋的表达方式。

【问题讨论】:

  • 使用find 而不是some

标签: javascript node.js lodash


【解决方案1】:

看起来您的输入数据是对象

变体 1. 使用 lodash pickBy

_.chain(arduair.aqi_ranges[pollutant])
    .pickBy(function(item, cat) {
        return _.inRange(
            c,
            item.range[0],
            item.range[1]
        )
    })
    .keys()
    .first() //remove this step if you want all mathed category
    .value();

变体 2. 使用 lodash reducefind(更可靠的变体)

_.chain(arduair.aqi_ranges[pollutant])
    .reduce(function(result, val, key) {
        return _.concat(
            result,
            _.merge(val, {category: key})
        );
     }, [])
     .find(function(item) { // use filter if you want all mathed category
         return _.inRange(
             c,
             item.range[0],
             item.range[1]
         );
      })
     .get('category')
     .value();

【讨论】:

    猜你喜欢
    • 2022-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    相关资源
    最近更新 更多