在angular/javascript中添加二维数组 [英] Adding two-dimensional arrays in angular/javascript

查看:60
本文介绍了在angular/javascript中添加二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在这里学习基本的javascript,请帮忙,添加二维数组,其中数组中第0个索引将始终是日期,第1个索引将始终是整数,我想要实现的是生成一个新数组通过添加其二维数组的第一个索引,唯一对象type = A和type = B.参见下面的示例代码

I am learning basic javascript here, please help, working on adding two-dimensional arrays, where 0th index will be always date and 1st index will be always integer in array, what i am trying to achieve is produce a new array with unique objects type=A and type=B by adding its 1st index of two-dimensional arrays. see below for example code

 $scope.mainArray = [{
    type: 'A',
    values: [
      [111111, 12],
      [111111, 12],
      [111111, 11],
      [111111, 2],
    ]
  }, {
    type: 'B',
    values: [
      [111111, 12],
      [111111, 12],
      [111111, 11],
      [111111, 2],
    ]
  }, {
    type: 'A',
    values: [
      [111111, 12],
      [111111, 12],
      [111111, 11],
      [111111, 2],
    ]
  }, {
    type: 'B',
    values: [
      [111111, 12],
      [111111, 12],
      [111111, 11],
      [111111, 2],
    ]
  }, ];

Should convert to

  $scope.newArray = [{
    type:'A',
    values:[
      [11111,24],
      [11111,24],
      [11111,22],
      [11111,4],
      ]
  },{
    type:'B',
    values:[
      [11111,24],
      [11111,24],
      [11111,22],
      [11111,4],
      ]
  }];

柱塞 链接

非常感谢您的帮助.

推荐答案

我看到您更新了代码段,因此这里是一个使用map/filter/reduce获取所需输出的示例.

I see that you updated the snippet so here is an example of using map/filter/reduce to get the output you're looking for.

  $scope.typeAArray = $scope.mainArray.filter(function (obj) {
    return obj.type === 'A';
  }).reduce(function (a, b) {
    var newObj = {
      type: a.type,
      values: []
    };
    a.values.map(function (v, index) {
      newObj.values.push(v);
      newObj.values[index][1] += b.values[index][1];
    });
    return newObj;
  });

这篇关于在angular/javascript中添加二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆