Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript – map items and extract items from sub array conditionally

How to extract items from a 2d array.

const array = [["1", "3"],["4", "3"]]
const itemToExclude = "3"

Use itemToExclude variable to exclude item from result (in this case 3)

Expected result is ["1", "4"]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const array = [["1", "3"],["4", "3"]]
const itemToExclude = "3"

const result = array.map((item) => {
   return item.map((subitem) => {
      return subitem
      // exclude itemToExclude
      })
    })
        
  console.log(result)

>Solution :

You can use Array flat and filter

const array = [
  ["1", "3"],
  ["4", "3"]
]
const itemToExclude = "3"

const result = array.flat().filter(item => item !== itemToExclude);
console.log(result)

You can also use reduce and inside the callback check if the element is not equals to itemToExclude

const array = [
  ["1", "3"],
  ["4", "3"]
]
const itemToExclude = "3"

const result = array.reduce((acc, curr) => {
  for (let i of curr) {
    if (i !== itemToExclude) {
      acc.push(i)
    }
  }

  return acc;
}, []);

console.log(result)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading