0

In the items array, it looks for objects with dates that are later than the current date, new Date (). let findObject = this.state.items.find (date => new Date (date.date)> new Date ()); I display the found dates on the page. Problem: let findObject = this.state.items.find (date => new Date (date.date)> new Date ()); finds only one object, and should find more.

Code here: https://stackblitz.com/edit/react-fm2g6y

class Item extends Component {

  render() {
    console.log(this.props.findObject);

    return (   
        <li>
          <div>
            {moment(this.props.findObject.date).format("YYYY-MM-DD")}
          </div>
        </li>
    )
  }
}


class App extends React.Component {
  constructor() {
    super();

    this.state = {

      items: [
        {
          id: 1,
          date: 'Sun Oct 01 2017 05:30:00 GMT+0530 (IST)'
        },
        {
          id: 2,
          date: 'Fri Aug 23 2019 05:30:00 GMT+0530 (IST)'
        },
        {
          id: 3,
          date: 'Wed Oct 23 2019 04:30:00 GMT+0530 (IST)'
        },
        {
          id: 4,
          date: 'Wed Oct 24 2019 05:30:00 GMT+0530 (IST)'
        },
        {
          id: 5,
          date: 'Thu Oct 05 2019 05:30:00 GMT+0530 (IST)'
        }]      
    };
  }


  render() {
    let findObject = this.state.items.find(date => new Date   (date.date) > new Date());

    return (
      <div>
        <ul>
          {
            this.state.items
              .map((item, index) =>
                <Item
                  key={index}
                  index={index}
                  item={item}
                  findObject = {findObject}
                />
              )
          }
        </ul>
      </div>
    );
  }
}

2 Answers 2

2

Replace this.state.items.find with this.state.items.filter if you need multiple results.

The find() method returns the value of the first element in the array that satisfies the provided testing function

Meaning it only returns first thing it matches with.

(ref https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)

On the other hand

The filter() method creates a new array with all elements that pass the test implemented by the provided function

meaning it will return multiple things it matches with

(ref https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)

Sign up to request clarification or add additional context in comments.

Comments

1

In render return before map add filter

this.state.items.filter(e => new Date(e.date) > new Date()).map(...)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.