Home > Blockchain >  Filter function with 2 array sets
Filter function with 2 array sets

Time:01-25

I am trying to achieve the same result as i wrote in below syntax by implementing filter function to my script.

The current script i have

    let sheet = [
        { $0: { 'Name': 'Report1' } },
        { $0: { 'Name': 'Row Count' } },
        { $0: { 'Name': 'Report2' } },
        { $0: { 'Name': 'User' } }
    ]

    let nope = ['User','Row Count','Container']
    let result = []

    for(let i = 0; i < sheet.length ;i  ){
        if(sheet[i].$0.Name != nope[0] && sheet[i].$0.Name != nope[1] && sheet[i].$0.Name != nope[2]){
            result.push(sheet[i])
        }
    }
    
    console.log(result)

On my browser inspect element, it will result of (2) [{…}, {…}] on console.log

I tried using filter function

    let result_2 = sheet.filter(w => !w.$0.Name.includes(nope[0]))
    console.log(result_2)

1 : One problem and logic i face is that im unsure on how can i includes all the element of 'nope' in 'includes()'
2 : I will have to hard code the index such as nope[0] which i dont think is advisable if its going to be a big array

CodePudding user response:

You actually almost finish but you reverse the w.$0.Name and nope.

let sheet = [
    { $0: { Name: "Report1" } },
    { $0: { Name: "Row Count" } },
    { $0: { Name: "Report2" } },
    { $0: { Name: "User" } },
];

let nope = ["User", "Row Count", "Container"];

let result_2 = sheet.filter(w => !nope.includes(w.$0.Name));

console.log(result_2);

PS: I think you should take a break and drink some tea. :)

CodePudding user response:

let result_2 = sheet.filter(w => !nope.includes(w.$0.Name))

CodePudding user response:

A simple and alternativr solution would be to use every() method within the filter. Like this:

It will check one element for every case of the second array and return true if nothing similar would be found.

 let result_2 = sheet.filter(w => nope.every(x=> x !== w.$0.Name))
    console.log(result_2)

let sheet = [{
    $0: {
      'Name': 'Report1'
    }
  },
  {
    $0: {
      'Name': 'Row Count'
    }
  },
  {
    $0: {
      'Name': 'Report2'
    }
  },
  {
    $0: {
      'Name': 'User'
    }
  }
]

let nope = ['User', 'Row Count', 'Container']
let result = []


let result_2 = sheet.filter(w => nope.every(x => x !== w.$0.Name))
console.log(result_2)

Or if you want to use includes() you can do this:

let result_3 = sheet.filter(w => !nope.includes(w.$0.Name))
    console.log(result_2)

let sheet = [{
    $0: {
      'Name': 'Report1'
    }
  },
  {
    $0: {
      'Name': 'Row Count'
    }
  },
  {
    $0: {
      'Name': 'Report2'
    }
  },
  {
    $0: {
      'Name': 'User'
    }
  }
]

let nope = ['User', 'Row Count', 'Container']
let result = []

let result_3 = sheet.filter(w => !nope.includes(w.$0.Name))
console.log(result_2)

Fiddle example

  •  Tags:  
  • Related