简体   繁体   English

向现有的数组数组添加值

[英]Adding values to existing array of arrays

I'm making an array that will look like this var qwe = [[a,b],[c],[d]] with the purpose of a and b being the identifiers. 我正在制作一个看起来像var qwe = [[a,b],[c],[d]]的数组,目的是a和b为标识符。

a - d are coming from reading the DOM. a-d来自读取DOM。 My current JS is doing what I want it to but I want to combine the similar arrays by their identifiers. 我当前的JS正在做我想要的,但是我想通过它们的标识符组合相似的数组。 Running the below code will give me 运行以下代码将给我

qwe =[
[100,200],[3],[2],  
[200, 300],[12],[4],    
[100,200],[2],[6]
]

but I want the final array to add the similar arrays by their identifiers so it will end up looking like (based on previous example) 但我希望最终数组通过其标识符添加相似的数组,以便最终看起来像(基于前面的示例)

qwe =[
[100,200],[5],[8],
[200, 300],[12],[4]
]

HTML HTML

<table name="tab" id="tab">
  <tr>
    <th>ID</th>
    <th>Location</th>
    <th>Value</th>
    <th>Other</th>
  </tr>
  <tr>
    <td><input name="itinValue" value="100"></td>
    <td><input name="location" value="200"></td>
    <td><input name="num" value='3'></td>
    <td><input name="other" value='2'></td>
  </tr>
  <tr>
    <td><input name="itinValue" value="200"></td>
    <td><input name="location" value="300"></td>
    <td><input name="num" value='12'></td>
    <td><input name="other" value='4'></td>
  </tr>
  <tr>
    <td><input name="itinValue" value="100"></td>
    <td><input name="location" value="200"></td>
    <td><input name="num" value='2'></td>
    <td><input name="other" value='6'></td>
  </tr>
</table>

JS JS

var table = document.querySelectorAll('[name="itinValue"]');
var qwe = [];

for(var i = 0; i < table.length; i++) {
  var a = document.getElementsByName('itinValue')[i].value;
  var b = document.getElementsByName('location')[i].value;
  var c = document.getElementsByName('num')[i].value;
  var d = document.getElementsByName('other')[i].value;
  var x = [[a,b],[c],[d]];

  //Compare,find,add here

  //if identifiers do not exist
  qwe.push(x);

}

This is a fiddle to my example that also correctly outputs the html too https://jsfiddle.net/3oge7wxg/125/ 这是我的例子的小提琴,它也可以正确输出html https://jsfiddle.net/3oge7wxg/125/

It looks like you want something called an associative array, "dict" in python, a key/value pairing, with the keys being your [a,b] part and the values your [c,d] parts. 看起来您想要一个称为关联数组的东西,即python中的“ dict”,一个键/值配对,其中键是您的[a,b]部分,而值是您的[c,d]部分。

You can emulate this in JavaScript through objects. 您可以通过对象在JavaScript中进行仿真。

Further reading is here: 进一步的阅读在这里:

You could try to find the item for updating and if not push the new array. 您可以尝试查找要更新的项目,如果没有,请推送新的数组。

 var table = document.querySelectorAll('[name="itinValue"]'), qwe = [], a, b, c, d, i, item; for (i = 0; i < table.length; i++) { a = +document.getElementsByName('itinValue')[i].value; b = +document.getElementsByName('location')[i].value; c = +document.getElementsByName('num')[i].value; d = +document.getElementsByName('other')[i].value; item = qwe.find(([[l, r]]) => l === a && r === b); if (item) { item[1][0] += c; item[2][0] += d; } else { qwe.push([[a, b], [c], [d]]); } } console.log(qwe); 
 <table name="tab" id="tab"> <tr> <th>ID</th> <th>Location</th> <th>Value</th> <th>Other</th> </tr> <tr> <td><input name="itinValue" value="100"></td> <td><input name="location" value="200"></td> <td><input name="num" value='3'></td> <td><input name="other" value='2'></td> </tr> <tr> <td><input name="itinValue" value="200"></td> <td><input name="location" value="300"></td> <td><input name="num" value='12'></td> <td><input name="other" value='4'></td> </tr> <tr> <td><input name="itinValue" value="100"></td> <td><input name="location" value="200"></td> <td><input name="num" value='2'></td> <td><input name="other" value='6'></td> </tr> </table> 

Version with Map . Map版本。

 var table = document.querySelectorAll('[name="itinValue"]'), qwe = [], a, b, c, d, i, item map = new Map; for (i = 0; i < table.length; i++) { a = +document.getElementsByName('itinValue')[i].value; b = +document.getElementsByName('location')[i].value; c = +document.getElementsByName('num')[i].value; d = +document.getElementsByName('other')[i].value; item = map.get([a, b].join('|')); if (item) { item[1][0] += c; item[2][0] += d; } else { item = [[a, b], [c], [d]] map.set([a, b].join('|'), item); qwe.push(item); } } console.log(qwe); 
 <table name="tab" id="tab"> <tr> <th>ID</th> <th>Location</th> <th>Value</th> <th>Other</th> </tr> <tr> <td><input name="itinValue" value="100"></td> <td><input name="location" value="200"></td> <td><input name="num" value='3'></td> <td><input name="other" value='2'></td> </tr> <tr> <td><input name="itinValue" value="200"></td> <td><input name="location" value="300"></td> <td><input name="num" value='12'></td> <td><input name="other" value='4'></td> </tr> <tr> <td><input name="itinValue" value="100"></td> <td><input name="location" value="200"></td> <td><input name="num" value='2'></td> <td><input name="other" value='6'></td> </tr> </table> 

I would use objects, just create a composite key: 我将使用对象,只需创建一个复合键:

var table = document.querySelectorAll('[name="itinValue"]');
var qwe = {};

for(var i = 0; i < table.length; i++) {
  var a = document.getElementsByName('itinValue')[i].value;
  var b = document.getElementsByName('location')[i].value;
  var c = new Number(document.getElementsByName('num')[i].value);
  var d = new Number(document.getElementsByName('other')[i].value);

  var key = a + "_" + b;

  previousValue = qwe[key];
  qwe[key] = previousValue ? [previousValue[0] + c, previousValue[1] + d] : [c, d];

}

You can convert to your desired array like so: 您可以像这样转换为所需的数组:

Object.keys(qwe).map(key => [key.split("_")].concat(qwe[key]));

https://jsfiddle.net/3oge7wxg/161/ https://jsfiddle.net/3oge7wxg/161/

Edit: Number constructors; 编辑:数字构造函数; Added fiddle 添加了小提琴

There are key facts I am taking note of in your question: 我在您的问题中注意到一些关键事实:

  • you are looping an array of data. 您正在循环数据数组。
  • you are storing data based on a key which is a tuple. 您正在基于作为元组的键来存储数据。
  • values where key is a match is an addition option. 键是匹配项的值是附加选项。
  • a,b,c,d are all ints,so if these are strings, you would need to run parseint() if they are strings. a,b,c,d都是整数,因此,如果它们是字符串,则如果它们是字符串,则需要运行parseint()。 This can be done by checking if it is currently type is a string, and if so, convert it. 这可以通过检查当前是否类型为字符串,如果是,则将其转换来完成。

Since it is a tuple and those are not implmented in javascript, you can do something like this. 由于这是一个元组,而javascript中没有这些元组,因此您可以执行以下操作。

var m = {};
var table = document.querySelectorAll('[name="itinValue"]');
for(var i = 0; i < table.length; i++) {

  var a = +document.getElementsByName('itinValue')[i].value;
  var b = +document.getElementsByName('location')[i].value;
  var c = +document.getElementsByName('num')[i].value;
  var d = +document.getElementsByName('other')[i].value;

  var key = a.toString() + "-" + b.toString();
  //creates key = "100-200"
  if (m[key]){
    m[key] = [m[key][0] + c, m[key][1] + d]
  }else{
    m[key] = [c,d]
  }
}

in the end, your map will now have unique keys and a map that looks like: 最后,您的地图现在将具有唯一键,并且地图看起来像:

{
  "100-200": [5,8],
  "200-300": [12,4]
}

and if for whatever reason, you need to break up they keys later, you just split on the key. 如果出于某种原因,您需要在以后拆分它们的密钥,则只需拆分密钥即可。 map.keys[index].split("-")

I think this is clean, but if you want to go a bit more, you could turn it into a class. 我认为这很干净,但是如果您想进一步学习,可以将其变成一堂课。

You then store the information in qwe. 然后,您将信息存储在qwe中。 If you need to, you can easily convert that from a map to a list, but it depends on your desired implementation goal. 如果需要,您可以轻松地将其从映射转换为列表,但这取决于所需的实现目标。 The key difference generally is whether or not you wish to maintain order. 通常,主要区别在于您是否希望维持订单。 qwe is populated only with this information, and given your comment based on this being your implementation not the best one, it gives me enough insight to believe that order isnt really as important as preservation of they key data elements, this key/tuple, and 2 values. qwe仅填充了此信息,并且鉴于您的评论不是您的最佳实现,因此它给了我足够多的见识,使我们相信顺序并不像保留关键数据元素,此关键/元组那样重要。 2个值。

If you know the amount of fields per row, here is an alternate way of retrieving your array. 如果您知道每行的字段数,这是检索数组的另一种方法。

var qwe = {};
var els = document.querySelectorAll('table#tab input');
for (i=0; i<els.length; i+=4) {
    var indexer = i < 4 ? 0 : i;
    var row = {
        a: [
            parseInt(els[indexer].value)
          , parseInt(els[indexer+1].value)
        ]
        , c: parseInt(els[indexer+2].value)
        , d: parseInt(els[indexer+3].value)
    };
    row.key = row.a.join('_');

    if (qwe[row.key]) {
        qwe[row.key][1][0]+=row.c;
        qwe[row.key][2][0]+=row.d;
    } else {
        qwe[row.key] = [row.a, [row.c], [row.d]];
    }
}

console.log( Object.values(qwe) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM