简体   繁体   中英

Copy values from one array to another, if condition satisfied

I have a matrix, that can vary in size. But for now, let's say it's a 6X6 matrix. It contains values on all the indexes, and some of these values can be 0.

Say the matrix looks like this:

var half_MW = [
    [0,1,1,0,0,0],
    [1,0,1,0,0,0],
    [1,1,0,0,0,0],
    [0,0,0,0,1,1],
    [0,0,0,1,0,1],
    [0,0,0,1,1,0]]

Now I want to create another array (lets call it data ), and copy only the values from half_MW that don't have 0 (ie (0,0) = 0, but also (0,3) = 0 etc.

What I'm not sure about, is how to create the array that I call data .

Here is my attempt

  var half_MW = ... (values shown above)
  var data = [];

  for(i = 0; i < 6; ++i) {
    var dataCols = [];
    for(j = 0; j < 6; ++j) {
      if(half_MW[i][j] != 0) {
        dataCols[i] = half_MW[i];
        dataCols[j] = half_MW[j];
      }     
    }

    data[i] = dataCols;

The result I get, is that the data/values are copied, but some indexes contain 0, which is what I don't want. So actually, data array, should not be a 6x6 array, it should be smaller, since those indexes from the half_MW array that contain 0 should be left out.

Your code do not work because you are missing dataCols.push(half_MW[i][j]); in the inner loop. Change that and it works:

 var half_MW = [ [0,1,1,0,0,0], [1,0,1,0,0,0], [1,1,0,0,0,0], [0,0,0,0,1,1], [0,0,0,1,0,1], [0,0,0,1,1,0]]; var data = []; for(i = 0; i < half_MW.length; ++i) { var dataCols = []; for(j = 0; j < half_MW[0].length; ++j) { if(half_MW[i][j] != 0) { dataCols.push(half_MW[i][j]); } } data[i] = dataCols; } console.log(data); 

You can also make the loop condition more dynamic by using half_MW.length for outer loop and half_MW[0].length for inner loop.

You could map the filtering with Boolean as callback.

 var half_MW = [[0, 0, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0], [1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1], [0, 0, 0, 1, 0, 1], [0, 0, 0, 1, 1, 0]], result = half_MW .map(a => a.filter(Boolean)) .filter(a => a.length); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

I would use a map to loop al the arrays and return them after you filter the condition out.

I this case it looks like you want to remove all the 0 s if not pliss comment so I can edit

Hope this helps :>

 var half_MW = [[0,1,1,0,0,0],[1,0,1,0,0,0],[1,1,0,0,0,0],[0,0,0,0,1,1],[0,0,0,1,0,1],[0,0,0,1,1,0]]; var data = half_MW.map(m=>{ return m.filter(c=> c!=0) }) console.log(data) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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