How can I sort an array by string?
const filter = [
{ index: "First" },
{ index: "Second" },
{ index: "Third" }
]
const data = [
{ title: 'Apple', index: "Second" },
{ title: 'Samsung', index: "First" },
{ title: 'BMW', index: "Third" },
{ title: 'Apple', index: "Second" },
{ title: 'Apple', index: "Second" },
{ title: 'Samsung', index: "First" }
]
Expected results:
const data = [
{ title: 'Samsung', index: "First" },
{ title: 'Samsung', index: "First" },
{ title: 'Apple', index: "Second" },
{ title: 'Apple', index: "Second" },
{ title: 'BMW', index: "Third" }
]
How to iterate over two arrays correctly? Do I have to iterate over two arrays to do this? Or is there another way to get the desired result?
Given three inputs - "First", "Second", "Third", if there will be more of these indices?
filterwas an array of strings instead of an array of objects. Then something likedata.sort((a, b) => filter.indexOf(a.index) - filter.indexOf(b.index))would be possible. ButfindIndexcould be used here as well.