Write a JavaScript program to perform stable sorting of an array, preserving the initial indexes of items when their values are the same. Do not mutate the original array, but returns a new array instead

  • برمجة جافاسكربت java script
  • برمجة

Write a JavaScript program to perform stable sorting of an array, preserving the initial indexes of items when their values are the same. Do not mutate the original array, but returns a new array instead. 

الأجوبة

const stableSort = (arr, compare) =>
  arr
    .map((item, index) => ({ item, index }))
    .sort((a, b) => compare(a.item, b.item) || a.index - b.index)
    .map(({ item }) => item);

const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(stableSort(arr, () => 0));
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...