0

As I mentioned in the title, I have a parameter that comes from the url and I have an array. If the name of the objects in this array and the parameter match, I want to show them first, then I can show the remaining data.

const {randomName} = useParams()
//randomName = "ASD"

//Example Object

const example = [{name:"bcd", size:32}, {name:"ASD", size:32} , {name:"ASD", size:32} , {name:"scd", size:32}, {name:"lgh", size:32} ]

example.map((x, index) => 
 <div> {x.name} {index} </div>
 )

//I want it rendered like this

ASD 1 
ASD 2
anyone 3
anyone 4
anyone 5
....





3 Answers 3

0

You have to sort the array

const randomName = "ASD"

const example = [{
  name: "bcd",
  size: 32
}, {
  name: "ASD",
  size: 32
}, {
  name: "ASD",
  size: 32
}, {
  name: "scd",
  size: 32
}, {
  name: "lgh",
  size: 32
}]

const result = [...example].sort((a, b) =>
  a.name === randomName ? -1 : b.name === randomName ? 1 : 0
).map((x, index) =>
  `<div> ${x.name} ${index} </div>`
)

console.log(result)

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

Comments

0

You could sort the wanted items to to and then map the result.

const
    value = "ASD",
    example = [{ name: "bcd", size: 32 }, { name: "ASD", size: 32 }, { name: "ASD", size: 32 }, { name: "scd", size: 32 }, { name: "lgh", size: 32 }];

example.sort((a, b) => (b.name === value) - (a.name === value));

console.log(example);

Comments

0

You could partition the data into two arrays, one of which has the ASD name and the rest that don't and then join the two arrays back together.

const example = [{name:"bcd", size:32}, {name:"ASD", size:32} , {name:"ASD", size:32} , {name:"scd", size:32}, {name:"lgh", size:32} ];

const partition = (data, partition_function) =>
  data.reduce(
    (acc, val) => (acc[+!partition_function(val)].push(val), acc),
    [[], []]
  );

const sort_asd_to_top = (data) =>
  partition(data, (val) => val.name === 'ASD').flat();

console.log(sort_asd_to_top(example));

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.