Search code examples
arraysreactjssortingreact-functional-component

How to change order of the specific object in react JS


I have buttons that are coming from API.

This is my buttons array output.

0: {uploaded: "User", id: 1, status: "A1"}
1: {uploaded: "User", id: 2, status: "A2"}
2: {uploaded: "User", id: 3, status: "A3"}
3: {uploaded: "User", id: 4, status: "A4"}
4: {uploaded: "User", id: 5, status: "A5"}
5: {uploaded: "User", id: 6, status: "A6"}



this is how I am mapping..

{buttons?.map((item) => (
    <Button
        outline
        key={item.id}
        disabled={isDisabled(item, status)}
        onClick={onTap.bind(null, item)}
        className={`statusName`}
    >
        {item.status}
    </Button>
))}

Now I have a requirement when status named status: "A6" is available in API response I need to show the order of my buttons as A1 A6 A2 A3 A4 A5 when status: "A6" not available in API response I need to show the order of my buttons as is not available A1 A2 A3 A4 A5. How I can change the order sorting based on status: "A6" value.


Solution

  • You can check if A6 is present and based on this use splice method to costruct new array

    export default function App() {
      let data = [
        { uploaded: "User", id: 1, status: "A1" },
        { uploaded: "User", id: 2, status: "A2" },
        { uploaded: "User", id: 3, status: "A3" },
        { uploaded: "User", id: 4, status: "A4" },
        { uploaded: "User", id: 5, status: "A5" },
        { uploaded: "User", id: 6, status: "A6" }
      ];
    
      let a6Idx = data.findIndex((obj) => obj.status === "A6");
      let newData = JSON.parse(JSON.stringify(data));
      if (a6Idx >= 0) {
        newData.splice(a6Idx);
        newData.splice(1, 0, data[a6Idx]);
      }
    
      return (
        <div>
          {newData.map((obj, idx) => (
            <button key={obj.id}>{obj.status}</button>
          ))}
        </div>
      );
    }
    

    sandbox