I want to sort an object by first Component came, not sort by identifier.

I mapped a object JSON and tried to use shift(), push(), forEach() but always return the object sort by identider. For my code:

listDices = [
{value: 1, hidden: false, id:0},
{value: 2, hidden: false, id:1},
{value: 6, hidden: false, id:2},
{value: 6, hidden: false, id:3},
{value: 5, hidden: false, id:4},
];

const arrMiniDices = [];
        listDices.map(item => {
            if (item.hidden) {
                arrMiniDices.push(
                        <BtnDice 
                            key={item.id}
                            value={item.value}
                            className="btn__dice--small"
                            onClick={() => this.handleHideDice(item.id)}
                        />
                )
            }
        });

I put arrMiniDices in a Component:

<ViewSectionToolsResult
      arrMiniDices={arrMiniDices}
/>

For example i have a Array:

const arr = [
{id0: "a"},
{id1: "b"},
{id2: "c"},
{id3: "d"},
{id4: "e"}
];

all items have onclick, when i click on "d", "b", "c", "a", "e" i want arrMiniDices =

[{id3: "d"},
{id1: "b"},
{id2: "c"},
{id0: "a"},
{id4: "e"}];

just by order of click But i have always

[{id0: "a"},
{id1: "b"},
{id2: "c"},
{id3: "d"}
{id4: "e"}];

2 Answers

0
Prithviraj Sahu On Best Solutions

You can keep another array to store the id the order in which dice are clicked. And use that array to load components.

Something similar to this:

const listDices = [
{value: 1, hidden: false, id:0},
{value: 2, hidden: false, id:1},
{value: 6, hidden: false, id:2},
{value: 6, hidden: false, id:3},
{value: 5, hidden: false, id:4},
];

const diceOrder = [];

handleDiceClick(diceId) {
  // ... Your stuff
  ...
  // update the dice order array
  // You need other logic to update the array. I am showing only adding.
  diceOrder.push(diceId);
}

const arrMiniDices = [];
diceOrder.map(id => {
  const item = listDices.find(dice => dice.id === id);
  if (item.hidden) {
    arrMiniDices.push(
      <BtnDice 
        key={item.id}
        value={item.value}
        className="btn__dice--small"
        onClick={() => handleHideDice(item.id)}
      />
    );       
  }
});

You have to use handleDiceClick somewhere.

0
Abdulla Thanseeh On

You could simply try to reverse the order that's all

suppose this is the final array

console.log(result)
//[{id2: "c"},{id1: "b"}];

console.log(result.reverse())

//[{id1: "b"},{id2: "c"}];

array.push will pop the lastin as first out by default