0

I have two arrays. They look like this but are longer in my code.

let arrayA = [{heading: "heading2", body: "text body2"}, {heading: "heading", body: "text body"}, {heading: "heading4", body: "text body4"}, {heading: "heading3", body: "text body3"}]
let arrayB = ["heading", "heading2", "heading 3", "heading 4"]

My html page needs to loop over arrayA and for each item return

<h1>item.heading</h1>
<p>item.body</p>

How would i go about sorting arrayA to get the same order as arrayB ?

  • Why is `arrayA` an array instead of an object like `{"heading2": "text body2", ...}` – Barmar Oct 27 '21 at 21:02
  • You can find multiple previous questions about how to sort an array of objects, or to sort based on another array, note that in your specific case you don't need to use the second array, having `arrayA.sort((a,b) => (a.heading > b.heading) ? 1 : -1 )` is enough – Zac Oct 27 '21 at 21:05
  • ArrayA contains articles, and each article is made of a heading and a body. – Meep Moop Sbap Oct 27 '21 at 21:07
  • Please note I do not want to sort them alphabetically, this might not be clear at first glance. They need to be sorted in the order of appearance of arrayB – Meep Moop Sbap Oct 27 '21 at 21:09
  • 1
    in this case you can refer to the answer here https://stackoverflow.com/a/44063445/2834925 and have `arrayA.sort((a, b) => arrayB.indexOf(a.heading) - arrayB.indexOf(b.heading));` – Zac Oct 27 '21 at 21:16
  • also note that the arrayB 3rd and 4th items are a bit different, there's a space before the number (3 & 4) – Zac Oct 27 '21 at 21:17

0 Answers0