Daryll
Daryll

Reputation: 571

How do I Sort, Slice, then Map an Array?

Im trying to sort, then slice (show last n elements of array only) and then map this array.

This is the working version (react syntax) currently, with sort and map but without slicing yet.

{Object.keys(dataObj)
                      .sort(
                        (a, b) =>
                          dataObj[a]["order"] -
                          dataObj[b]["order"]
                      )
                      .map((movie, i) => {
                        return (
                          <li key={i}>
                            {movie}
                            {dataObj[movie]["value"]}
                          </li>
                        );
                      })}

How do I continue to slice this, in between sort and map?
This is what my pseudo code would look like.

{Object.keys(dataObj)
                      .sort(
                        (a, b) =>
                          dataObj[a]["order"] -
                          dataObj[b]["order"]
                      )
                      .((arr)=>arr.slice(arr.length-10, arr.length+1))
                      .map((movie, i) => {
                        return (
                          <li key={i}>
                            {movie}
                            {dataObj[movie]["value"]}
                          </li>
                        );
                      })}

This obviously does not work but how do I carry on to Slice after the .sort which returns an array?
And then map this sliced array afterwards.
What syntax do I use? Thanks!

Upvotes: 0

Views: 2245

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386756

You could take Array#slice directly with a negative index from the end.

Object.keys(dataObj)
    .sort((a, b) => dataObj[a].order - dataObj[b].order)
    .slice(-10)
    .map((movie, i) => {
        return (
            <li key={i}>
               {movie} {dataObj[movie].value }
            </li>
        );
    })

Upvotes: 4

Related Questions