How to get data that satisfies a condition from multiple data in JavaScript (map/filter)

Viewed 30

How to select data that satisfies a condition from multiple data.

I'm not good at using maps and filters. How to select data that satisfies a condition from multiple data.

sampleData

[
    {
        "dataList": [
            {
                "date": "2022-09-01T15:00:00Z",
                "friendsIds": []
            },
            {
                "date": "2022-09-02T15:00:00Z",
                "friendsIds": []
            },
            {
                "date": "2022-09-03T15:00:00Z",
                "friendsIds": []
            },
            {
                "date": "2022-09-04T15:00:00Z",
                "friendsIds": [
                    6
                ]
            },
            {
                "date": "2022-09-05T15:00:00Z",
                "friendsIds": [
                    7,8,10
                ]
            },
            {
                "date": "2022-09-06T15:00:00Z",
                "friendsIds": [
                    8
                ]
            },
            {
                "date": "2022-09-09T15:00:00Z",
                "friendsIds": [
                    9
                ]
            },
        ]
    }
]

I want to get the first time when frends is not empty. However, the last time is obtained. And there is a type error.

  const sample = React.useMemo(() => {
    let arr[]:string[];
    sampleData[0].dataList.map((list) => {
      if(list.friends.length > 0) {
        result = list.date;
        return result;
      }
    });
    return result;
  }, [sampleData]);

 console.log(sample);

result

2022-09-09T15:00:00Z

expectation

2022-09-04T15:00:00Z
1 Answers

Use array.find for this:

  const sample = React.useMemo(() => {
    return sampleData[0].dataList.find(x => x.friends.length)?.date
  }, [sampleData]);
Related