【问题标题】:Mapping collection based on how many times item been called根据项目被调用的次数映射集合
【发布时间】:2015-08-15 17:24:28
【问题描述】:

下面我有一个arrary (arr) 包含objects 和两个属性idcontent,我需要映射到这个array 并返回和array,其中项目与相同的id 是数组中的shift,按从左到右的顺序排列。

var arr = [
  {
    'id': '32423423',
    'content': ['one']
  },
  {
    'id': '23456789',
    'content': ['one', 'two', 'three']
  },
  {
    'id': '23456789',
    'content': ['one', 'two', 'three']
  },
  {
    'id': '23456789',
    'content': ['one', 'two', 'three']
  }
  {
    'id': '13123123',
    'content': ['two']
  }
]

期望的输出是这样的:

var output = [
  'one',
  'one',
  'two',
  'three'.
  'two'
]

content 项的数组。

【问题讨论】:

  • 所以,基本上,您需要删除重复项,然后创建一个仅包含每个 content 属性中剩余项的数组?
  • 不,我需要重复 @taylorc93 在下面查看我的答案

标签: javascript arrays object dictionary lodash


【解决方案1】:

我会为此使用reduce()

_.reduce(arr, function(result, item) {
    this.push(item.id);
    return result.concat(item.content[_.countBy(this)[item.id] - 1]);
}, [], []);

您会注意到在 iteratee 函数之后有两个数组传入reduce()。第一个数组是累加器,用于构建我们的结果。第二个数组是函数上下文——这是一个用来避免在函数外部创建全局变量的小技巧。我们需要一个来跟踪 ID。

我们在回调函数中做的第一件事就是将item.id 添加到所见ID 列表中(this)。然后我们将适当的content 连接到结果中,然后转到下一项。

我们跟踪 ID 的原因是我们可以使用 countBy() 计算每个唯一 ID 的数量。这就是我们根据重复 ID 的数量计算出content 的索引位置的方法。

【讨论】:

    【解决方案2】:
    var _ = require('lodash')
    
    function mapShiftOver (data, item) {
      var master = _.chain(data).indexBy(item).values().value()
      return _.map(data, function (item) {
        var masterItem = _.find(master, {
          'item': item.id
        })
        if (!masterItem) return undefined
        return masterItem.content.shift()
      })
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-15
      • 1970-01-01
      • 2013-06-13
      • 2013-01-07
      • 2013-02-03
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      • 2019-04-06
      相关资源
      最近更新 更多