Created
November 19, 2021 08:33
-
-
Save nopresnik/7339de56c6dc958b254bece0f03749a8 to your computer and use it in GitHub Desktop.
Re order a list of people and persist it in the person object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Person { | |
order: number; | |
name: string; | |
} | |
function reOrderPeople(people: Person[], person: Person, newOrder: number) { | |
const personIndex: number = people.findIndex((l) => l.name === person.name); | |
people.splice(personIndex, 1); | |
people.splice(newOrder - 1, 0, person); | |
return people.map((person, index) => ({ ...person, order: index + 1 })); | |
} | |
const peopleList: Person[] = [ | |
{ order: 1, name: "Nathan Opresnik" }, | |
{ order: 2, name: "John Doe" }, | |
{ order: 3, name: "Alex Jones" } | |
]; | |
console.log(reOrderPeople(peopleList, { order: 3, name: "Alex Jones" }, 2)); | |
// Result: [ | |
// { order: 1, name: "Nathan Opresnik" }, | |
// { order: 2, name: "Alex Jones" }, | |
// { order: 3, name: "John Doe" } | |
// ]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment