SkyeBoniwell
SkyeBoniwell

Reputation: 7122

Sorting an array alphabetically before filtering and mapping it

I'm generating a drop down list with a React component.

I want to sort the array before I filter and map it out, but it keeps saying:

data.sort.filter is not a function

But I looked up arrays and javascript, and I do see a method called 'sort' so I'm not sure why it's not letting me sort it.

Here is my code:

const OptionList = () => {

    const [data, setData] = useState([]);

    useEffect(() => {
        const fetchData = async () => {
            const result = await axios(
                'api/departments',
            );
            setData(result.data);
            console.log(JSON.stringify(result, null, 2));
        };
        fetchData();
    }, []);

    return (
        <>
            {data.sort.filter(item => item.groupById === 2).map((item, index) => (
                <option key={index} value={item.id} label={item.name} />
            ))}

            <optgroup label="Other"></optgroup>
            {data.sort.filter(item => item.groupById === 1).map((item, index) => (
                <option key={index} value={item.id} label={item.name} />
            ))}
        </>

    );
}
export default OptionList;

The data in 'data' is an array of objects that look like this:

{
  "id": 34,
  "name": "Massive Gaming Hillbilly Club",
  "groupById": 2
},

What could I be doing wrong?

Thanks!

Upvotes: 1

Views: 1983

Answers (3)

Wouter van Nifterick
Wouter van Nifterick

Reputation: 24116

You're not calling the sort function. You probably meant something like:

data.sort().filter( ..... )

You'll also have to pass a function to compare items to the sort function to tell it how to sort.

As @HMR mentioned, sort() mutates data in this case, which you probably don't want at this place in your code. You could make a copy, or do the sorting elsewhere.

Upvotes: 2

HMR
HMR

Reputation: 39320

If you want to sort by name property and I assume it's a string then you can do:

{[...data].sort((a,b)=>a.name.localeCompare(b.name)).filter

I am copying data first because sort will mutate it.

You can also sort it when you set the state:

setData(result.data.sort((a,b)=>a.name.localeCompare(b.name)));

Here I am mutating data because it came from axios and after setting state you don't use it anymore.

Upvotes: 2

Person
Person

Reputation: 2269

Sort is a function, so you need to call it

data.sort().filter(...)

Upvotes: 1

Related Questions