make an array with a specific order. iterate over an array of object and render it the giving order in typescript
index.ts
// Define an array with specific orderconst order = ['b', 'a', 'c'];
// Original array of objectsconst data = [{ id: 'a', value: 1 }, { id: 'b', value: 2 }, { id: 'c', value: 3 }];
// Create an object to easily look up the index of each id in the order arrayconst indexLookup = order.reduce((acc, curr, index) => {
acc[curr] = index;
return acc;
}, {} as { [key: string]: number });
// Sort the data array based on the defined orderconst sortedData = data.sort((a, b) => indexLookup[a.id] - indexLookup[b.id])
// Rendering data in the order specifiedsortedData.forEach(obj => {
console.log(obj); // Render each object based on the specified order});
666 chars
20 lines
If you have an array of objects and you want to render them in the specific order defined by another array, you can achieve this by sorting the array of objects based on the custom order specified.