मान लीजिए, हमारे पास ऑब्जेक्ट्स का निम्नलिखित एरे है जो इसके id प्रॉपर्टी के अनुसार सॉर्ट किया गया है -
const unordered = [{ id: 1, string: 'sometimes' }, { id: 2, string: 'be' }, { id: 3, string: 'can' }, { id: 4, string: 'life' }, { id: 5, string: 'tough' }, { id: 6, string: 'very' }, ];और स्ट्रिंग का एक और एरे इस तरह -
const ordered = ['Life', 'sometimes', 'can', 'be', 'very', 'tough'];
हमें पहले एरे को सॉर्ट करना है ताकि इसकी string प्रॉपर्टी का क्रम दूसरे एरे में स्ट्रिंग के क्रम के समान हो। इसलिए, आइए इसके लिए कोड लिखते हैं।
उदाहरण
const unordered = [{ id: 1, string: 'sometimes' }, { id: 2, string: 'be' }, { id: 3, string: 'can' }, { id: 4, string: 'life' }, { id: 5, string: 'tough' }, { id: 6, string: 'very' }, ]; const ordered = ['Life', 'sometimes', 'can', 'be', 'very', 'tough']; const sorter = (a, b) => { return ordered.indexOf(a.string) - ordered.indexOf(b.string); }; unordered.sort(sorter); console.log(unordered);आउटपुट
कंसोल में आउटपुट होगा -
[ { id: 4, string: 'life' }, { id: 1, string: 'sometimes' }, { id: 3, string: 'can' }, { id: 2, string: 'be' }, { id: 6, string: 'very' }, { id: 5, string: 'tough' } ]