Home > OS >  use every and filter function together in JavaScript
use every and filter function together in JavaScript

Time:12-04

I have two arrays of strings. where I want to see if one array has any value common from another array and then print the array which has unique values only. For this I am performing a JavaScript every function on both the arrays which returns a Boolean if one array has values common from another array and then if the condition is true, I am doing a filter on an array to show the data. Here are the arrays:

marketingCarrierCode: ["DL", "AA"]
operatingCarrierCode: ["AA", "AA"]

now I am doing every and filter like this way:

const hasSameCarrierCode = operatingAirlineCode.every(
    code => marketingAirlineCode.indexOf(code) !== -1,
  );
  const listOfOperatingCarriers = operatingAirlineCode.filter(
    code => marketingAirlineCode.indexOf(code) === -1,
  );

this gives me:

hasSameCarrierCode: true
listOfOperatingCarriers: []

now I want to perform every and filter function in one function, how can I do that?

CodePudding user response:

Doesn't need to first function. You can use thie:

const listOfOperatingCarriers = operatingAirlineCode.filter(
  code => marketingAirlineCode.indexOf(code) === -1,
);

listOfOperatingCarriers.length !== operatingAirlineCode.length   => true,
listOfOperatingCarriers => []

CodePudding user response:

In your sample code, "for each" code in operatingCarrierCode, you are checking if it exists in marketingAirlineCode. If any code doesn't exist in marketingAirlineCode, then test is failed i.e. hasSameCarrierCode should be false. Also, you add the uncommon code in list listOfOperatingCarriers. All this can be combined into one forEach as below:

const marketingAirlineCode = ["DL", "AA"]
const operatingCarrierCode = ["AA", "AA"]

let hasSameCarrierCode = true;
let listOfOperatingCarriers = [];

operatingCarrierCode.forEach(code => {
  if (marketingAirlineCode.indexOf(code) === -1) {
    hasSameCarrierCode = false;
    listOfOperatingCarriers.push(code);
  }
})

console.log(`hasSameCarrierCode:`, hasSameCarrierCode)
console.log(`listOfOperatingCarriers:`, listOfOperatingCarriers);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

A much smaller version could be:

const marketingAirlineCode = ["DL", "AA"]
const operatingCarrierCode = ["AA", "AA"]

const listOfOperatingCarriers = operatingCarrierCode.filter(code => marketingAirlineCode.indexOf(code) === -1);
const hasSameCarrierCode = listOfOperatingCarriers.length === 0;

console.log(`hasSameCarrierCode:`, hasSameCarrierCode)
console.log(`listOfOperatingCarriers:`, listOfOperatingCarriers);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related