1

I want to display array values using map in jsx, but don't want to create element for undefined value. here in below example, mainArray has multiple subarrays, and in last array, last element is undefined. and unnecessary list is getting created for undefined value.

import "./styles.css";

export default function App() {
const d=['link1','link2','link3','link4','link5'];
const mainArr=[];
  var a=[];
  var b=[];
  var c=[];
  for(var i=0;i<d.length;i=i+3){
    a.push(d[i]);
    b.push(d[i+1]);
    c.push(d[i+2]);
   }
  mainArr.push(a,b,c);
   
  
  return (
    <div>
      {
      mainArr.map((link,ind) => {
       return (
          <div>
            <ul>
            {/* <div>{ind}</div> */}
            {
              link.map(item=> {
                return(
                  <li>{item}</li>
                )
              })
            }
            </ul>
          </div>
        )
      })
    }
  </div>
  );
  }
MikeOne
  • 4,789
  • 2
  • 26
  • 23
Supriya Kumari
  • 181
  • 2
  • 14
  • have you thought about filtering the array before using it? Remove all the undefined elements and then use it – Synapsis Mar 23 '22 at 21:08
  • 2
    Either the suggestion above or you can do a check to see if item exists. `{item &&
  • {item}
  • ` – fynmnx Mar 23 '22 at 21:10
  • `yourArray.filter(Boolean).map` should do it. – Brian Thompson Mar 23 '22 at 21:12
  • Does this answer your question? [Removing undefined values from Array](https://stackoverflow.com/questions/28607451/removing-undefined-values-from-array) – Brian Thompson Mar 23 '22 at 21:12
  • item &&
  • {item}
  • , this solution is working fine – Supriya Kumari Mar 23 '22 at 21:13