Home > Blockchain >  Why is this 2D array filtering not working?
Why is this 2D array filtering not working?

Time:05-07

I have this 2D array and I'm trying to filter it, but it's coming out unfiltered:

Data:

[
 ["Val #","Val #","Val #","Val #","Val #"],
 ["SO-000379-001A-047-1","SO-000379-001A-047-2","-","-","-"]
]

Filtering line:

cads = cads.filter(e => e[1] != "-" || e[1] != '');

Expected result:

[
 ["Val #","Val #"],
 ["SO-000379-001A-047-1","SO-000379-001A-047-2"]
]

WTHeck am I missing?

Thank you!

CodePudding user response:

it should be

const data = [
 ["Val #","Val #","Val #","Val #","Val #"],
 ["SO-000379-001A-047-1","SO-000379-001A-047-2","-","-","-"]
]

const result = data.map(d => d.filter(v => !['', '-'].includes(v)))

console.log(result)

you want to filter out the inner arrays not the main one

so you have to map each external array and then filter the single rows

CodePudding user response:

Is this what you need? Filter items based on x and y axis.

const cads = [
  ["Val #", "Val #", "Val #3", "Val #", "Val #"],
  ["SO-000379-001A-047-1", "-", "SO-000379-001A-047-2", "-", "-"]
]

function f(data) {
  if (!(data && data.length)) {
    return []
  }
  const v = []
  const m = data.length;
  const n = data[0].length;
  const check = (x) => x !== '-' && x !== ''
  for (let i = 0; i < n; i  ) {
    let f = true
    for (let j = 0; j < m; j  ) {
      if (!check(data[j][i])) {
        f = false
        break;
      }
    }
    if (f) {
      for (let k = 0; k < m; k  ) {
        v[k] = v[k] || []
        v[k].push(data[k][i]);
      }
    }
  }
  return v
}
console.log(f(cads))

CodePudding user response:

let data = [
 ["Val #","Val #","Val #","Val #","Val #"],
 ["SO-000379-001A-047-1","SO-000379-001A-047-2","-","-","-"]
]

for (let i = 0; i <= data[1].length; i  ) {
    if(data[1][i] === "-"){
        data[0].splice(i,1);
        data[1].splice(i,1);
        i--;
    }
}

console.log(data);

Not smart enough to use those Array.map/filter function, but I guess this is what you want?

CodePudding user response:

Description

I believe what you are looking for is a way to filter both rows of the array based on the items in the second row. Here is an example of how to do that. I changed your data slightly to show that it is filtering row 1.

Script

function test() {
  try {
    let data = [ ["Val 1","Val 2","Val 3","Val 4","Val 5"],
                  ["SO-000379-001A-047-1","","SO-000379-001A-047-2","-","-"] ];
    let result = [[],[]];
    data[1].forEach( (item,i) => {
      if( (item != "-") && (item != "") ) {
        result[0].push(data[0][i]);
        result[1].push(data[1][i]);
      }
    });
    console.log(result);
  }
  catch(err) {
    console.log(err);
  }
}

Console.log

8:23:57 AM  Notice  Execution started
8:23:58 AM  Info    [ [ 'Val 1', 'Val 3' ],
  [ 'SO-000379-001A-047-1', 'SO-000379-001A-047-2' ] ]
8:23:57 AM  Notice  Execution completed
  • Related