Home > Net >  Get non empty items in array map in react native
Get non empty items in array map in react native

Time:04-21

I have react native Loop to fill the select Items like below

   const categorylist = arr.map((data, key) => {
      if (data != "") {
        return <Select.Item label={data} value={data} key={data} />;
      }
    });

I loop and use it like below , it works fine when array contains non empty values, but when there is empty values i get the error

TypeError: null is not an object (evaluating 'child.props')

   <Select>
     {categorylist2}
    </Select>

How do i send only non empty array items using map. please note i don't want arr to be affected as i need it unchanged in other functions.

CodePudding user response:

filter out the empty elements then map over the array filter returns.

Here's a contrived example to show you how it works.

const arr = [undefined, 'Bob', '', 'Sally', 'Joe', '', null, 'Pam'];

// `filter` out the empty/null/undefined elements
// and then `map` over that filtered array
const out = arr
  .filter(el => el)
  .map(el => `<div>${el}</div>`);

document.body.innerHTML = out.join('');

CodePudding user response:

You need to map through the array only if the array is not empty and use filter(Boolean) to filter out empty ones.

const newArr = arr.filter(Boolean);
const categorylist = (newArr.length > 0) && newArr.map((data, key) => {
    return <Select.Item label={data} value={data} key={data} />;
});

CodePudding user response:

It is because in your map you do not return anything for empty values, which means null that's why you have the error. A map function should always return something.

Use filter before map like so:

arr.filter(data => data !== "").map(data => <Select.Item label={data} value={data} key={data} />)

CodePudding user response:

It can be achieved by reducer function.

Using Array.filter() then Array.map() traverses the array twice, but you can achieve the same effect while traversing only once with Array.reduce(), thereby being more efficient.

More about it here

const categorylist = arr.reduce((prev, current, index) => {
      if (current != "") {
        prev.push(<Select.Item label={current} value={current} key={current} />);
      }
      return prev;
    }, []);
    
    console.log(categorylist);
  • Related