PASSWORD RESET

Your destination for complete Tech news

How to remove empty elements from an array in React JS?

1.45K 0
< 1 min read

To remove empty or falsy elements from an array in React or JavaScript, you can use the filter() method. The filter() method creates a new array containing only the elements that pass a certain condition. In this case, you can filter out empty or falsy elements. Here’s how you can do it:

import React from 'react';

function RemoveEmptyElements() {
  const originalArray = [1, '', 3, null, 5, undefined, 7, false, 9];
  const filteredArray = originalArray.filter(element => element);

  return (
    <div>
      <p>Original Array: {originalArray.join(', ')}</p>
      <p>Filtered Array: {filteredArray.join(', ')}</p>
    </div>
  );
}

export default RemoveEmptyElements;

In this example, the RemoveEmptyElements component filters the originalArray using the filter() method with a simple identity function element => element to remove falsy values (empty strings, null, undefined, false, etc.).

The filteredArray will only contain truthy values from the originalArray. The join(', ') method is used to format the array elements for display.

Replace [1, '', 3, null, 5, undefined, 7, false, 9] with your own array, and the component will display both the original and filtered arrays.

Keep in mind that this approach removes values that are falsy, not just empty strings. If you specifically want to remove only empty strings, you can modify the condition inside the filter() function accordingly.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.