【问题标题】:How to bin data in an array but include the previous value?如何将数组中的数据合并但包含先前的值?
【发布时间】:2018-10-02 06:39:47
【问题描述】:

我有一个名为 targetPercentage 的数组。

targetPercentage = [0,33,77,132]

如何将它分成长度为 2 的块,但包含前一个值? 如果可能的话,也可以把它做成一个带有各自属性的 Javascript 对象数组。

示例输出:

[0,33]
[33,77]
[77,132]

通过将其转换为对象数组的示例输出:

thresholds : [ {from:0,to:33},{from:33,to:77},{from:77,to:132} ] 

类似于 question 的东西,但包含之前的值。

【问题讨论】:

  • [from:0,to:33] 是无效语法,我猜你的意思是它是一个对象,而不是一个数组?
  • 他只是一个例子。
  • @CertainPerformance 修复了它。对此深表歉意。
  • 呃,它仍然无效 - 对象需要同时具有键和值。我猜你正在寻找 [ {from:0,to:33},{from:33,to:77},{from:77,to:132} ][ [0,33],[33,77],[77,132] ]

标签: javascript arrays


【解决方案1】:

您可以使用Array.from 从头开始​​创建数组,并在每次迭代时访问ith 元素以及i + 1th 元素以创建对象:

const targetPercentage = [0,33,77,132];
const result = Array.from(
  { length: targetPercentage.length - 1 },
  (_, i) => ({ from: targetPercentage[i], to: targetPercentage[i + 1] })
);
console.log(result);

或者如果您想要一个数组数组:

(_, i) => ([ targetPercentage[i], targetPercentage[i + 1] ])

【讨论】:

    【解决方案2】:
    const targetPercentage = [0, 33, 77, 132]
    
    const thresholds = []
    for (let i = 0; i < targetPercentage.length - 1; i++) {
    let range = {
      from: targetPercentage[i],
      to: targetPercentage[i + 1]
     }
     thresholds.push(range) 
    }
    

    【讨论】:

    • 虽然此代码可能(或可能不会)解决问题,但一个好的答案应该解释代码的作用以及它如何解决问题。
    【解决方案3】:

    你可以试试这个:

    function binData(array) {
      let result = []
    
      for (let i=0; i<array.length-1; i++) {
        result.push({
          from: array[i],
          to: array[i+1]
        })
      }
    
     return result
    }
    

    【讨论】:

      【解决方案4】:

      array function-slice(initial,count) - 将给定的数组分成 3 块,每块 2 个元素。

      临时数组将有[0,33],[33,77],[77,132]

       var i,j,temparray,chunk = 2;
              result=[];for (i=0,j=targetPercentage.length; i<j-1; i++) {
                  temparray = targetPercentage.slice(i,i+chunk);
                 result.push({from:temparray[0],to:temparray[1]});
              }
              console.log(result);
      

      【讨论】:

      • 虽然此代码可能(或可能不会)解决问题,但一个好的答案应该解释代码的作用以及它如何解决问题。
      猜你喜欢
      • 1970-01-01
      • 2014-08-01
      • 2018-11-08
      • 2017-01-16
      • 1970-01-01
      • 2021-12-20
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多