1

const apiUrl2 = `https://api.quran.com/api/v4/verses/random?language=en&words=true&translations=en&audio=1&tafsirs=en`;
    fetch(apiUrl2)
        .then((response) => response.json())
        .then(data => {

            console.log(data);
            for (let i = 0; i < data.verse.words.length; i++) {
                // var result = Object.values(data.words[i]);
                let datas = data.verse.words[i];
                console.log(datas.translation.text);
                // console.log(datas.sort());
                let sorted=datas.position;
                const propertyNames=Object.keys(sorted); 
                console.log(sorted);
                
                // console.log(result.sort());
                // document.getElementById('hadithNumber').innerHTML += ' ' + sorted.sort();
                // if (datas.position <= i) {
                //     let ayah = [];
                //     ayah.push();
                //     console.log(ayah[i]);
                // }
            }
        })
        .catch(error => {
            console.log(error);
        });

So Basically, I've this API to fetch Holy Quran Ayat/Verses in this API we have a key called Position according to which the words has to be shown to make the Ayat complete. JSON

"verse": {
    "id": 5890,
    "verse_number": 6,
    "verse_key": "84:6",
    "hizb_number": 59,
    "rub_el_hizb_number": 236,
    "ruku_number": 528,
    "manzil_number": 7,
    "sajdah_number": null,
    "page_number": 589,
    "juz_number": 30,
    "words": [
        {
            "id": 6721,
            "position": 2,
            "audio_url": "wbw/084_006_002.mp3",
            "char_type_name": "word",
            "code_v1": "ﭲ",
            "page_number": 589,
            "line_number": 6,
            "text": "ﭲ",
            "translation": {
                "text": "mankind",
                "language_name": "english"
            },
            "transliteration": {
                "text": "l-insānu",
                "language_name": "english"
            }
        },
        {
            "id": 6722,
            "position": 3,
            "audio_url": "wbw/084_006_003.mp3",
            "char_type_name": "word",
            "code_v1": "ﭳ",
            "page_number": 589,
            "line_number": 6,
            "text": "ﭳ",
            "translation": {
                "text": "Indeed, you",
                "language_name": "english"
            },
            "transliteration": {
                "text": "innaka",
                "language_name": "english"
            }
        },
        {
            "id": 6723,
            "position": 4,
            "audio_url": "wbw/084_006_004.mp3",
            "char_type_name": "word",
            "code_v1": "ﭴ",
            "page_number": 589,
            "line_number": 6,
            "text": "ﭴ",
            "translation": {
                "text": "(are) laboring",
                "language_name": "english"
            },
            "transliteration": {
                "text": "kādiḥun",
                "language_name": "english"
            }
        },....}

As you can see in the response in words array we have a key called position we need to use that key to sort it and add text based on its value This is what I've tried till now.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • Can lodash [orderBy](https://lodash.com/docs/4.17.15#orderBy) help – Azzy Nov 30 '22 at 13:29
  • I'm mostly looking for the Vanilla JavaScript Solution, But thanks will sure try with Lodash as well. :) – NewBie_WannaBe Nov 30 '22 at 13:31
  • 1
    @NewBie_WannaBe ... any array's [`sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) method accepts a callback function. Within this callback one can implement ones own sorting rules by always comparing the two passed items/value and then upon the comparison result returning a value according to the compared items sort order which is ... grater than zero for descending order, lower than zero for ascending order and zero for no position change. thus ... `data.verse.words.sort((a, b) => a.position - b.position);` – Peter Seliger Nov 30 '22 at 13:38
  • Does this answer your question? [Sort array of objects by string property value](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value) – wei Nov 30 '22 at 13:53

4 Answers4

2

You can create your own comparison function.

function compare(a, b) {
    return a.position - b.position;
}

const apiUrl2 = `https://api.quran.com/api/v4/verses/random?language=en&words=true&translations=en&audio=1&tafsirs=en`;
fetch(apiUrl2)
    .then((response) => response.json())
    .then(data => {

        console.log(data);
        data.verse.words.sort(compare);
        for (let i = 0; i < data.verse.words.length; i++) {
            // var result = Object.values(data.words[i]);
            let datas = data.verse.words[i];
            console.log(datas.translation.text);
            // console.log(datas.sort());
            let sorted = datas.position;
            const propertyNames = Object.keys(sorted);
            console.log(sorted);

            // console.log(result.sort());
            // document.getElementById('hadithNumber').innerHTML += ' ' + sorted.sort();
            // if (datas.position <= i) {
            //     let ayah = [];
            //     ayah.push();
            //     console.log(ayah[i]);
            // }
        }
    })
    .catch(error => {
        console.log(error);
    });
wei
  • 937
  • 2
  • 14
  • 34
  • 1
    @NewBie_WannaBe ... in the OP's case something more simple like `return a.position - b.position;` already does the job. – Peter Seliger Nov 30 '22 at 13:40
  • why write your own function when you have something built-in like `array.sort()` for this exact scenario? – Pratik Dev Nov 30 '22 at 13:44
  • @PratikDev because OP wanted to sort array of objects by property value – wei Nov 30 '22 at 13:47
  • @PratikDev ... the above provided solutions uses a `sort` callback; it's named `compare`. Just the callback's implementation is not as straightforward as it could be (like e.g. proposed with your solution which therefore received an upvote too). – Peter Seliger Nov 30 '22 at 13:48
  • @PeterSeliger when we write a function, it uses storage in the browser. so implementing a whole new function for something that we can achieve through some built-in functions, is similar to keeping a copy of a file in your C-Drive and you're using only one – Pratik Dev Nov 30 '22 at 14:01
  • @PratikDev ... I really do not know what you're talking about ... the above answer suggests exactly the same what you did. Your code comes with a `sort` callback provided as lambda expression (your anonymous function expression) whereas the above answer implements the `sort` callback as `compare` function statement. Both solutions makes use of `sort`. They differ in how the `sort` callback got implemented. Btw ... it is not necessary to assign the sorted array to an extra variable like with your solution ... `sort` mutates the array it is called upon. – Peter Seliger Nov 30 '22 at 14:35
1

sort the words array before looping through it with array.sort()

here's an example below:

const array = [
  {text: "John", position: 34},
  {text: "Peter", position: 54},
  {text: "Jake", position: 25},
  {text: "Jolly", position: 2},
];

let sorted_array = array.sort(function(a, b) {
  return a.position - b.position; // sorts the "words" array based on the value of "position"
});

console.log(sorted_array)

now you can run your loop with the new sorted_array

Pratik Dev
  • 304
  • 2
  • 8
0

Try Below

const list = data.verse.words;
list.sort((a,b) => a.position - b.position);
const orderedTextArray = list.map((wordModel) => wordModel.translation.text);
const result = orderedTextArray.join(' ');
Rahul Beniwal
  • 639
  • 4
  • 9
-1

I think Array.sort() is what you're looking for

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#sorting_array_of_objects

//this snippet comes from the above page, credit goes to its author
const items = [
  { name: "Edward", value: 21 },
  { name: "Sharpe", value: 37 },
  { name: "And", value: 45 },
  { name: "The", value: -12 },
  { name: "Magnetic", value: 13 },
  { name: "Zeros", value: 37 },
];

// sort by value
items.sort((a, b) => a.value - b.value);

// sort by name
items.sort((a, b) => {
  const nameA = a.name.toUpperCase(); // ignore upper and lowercase
  const nameB = b.name.toUpperCase(); // ignore upper and lowercase
  if (nameA < nameB) {
    return -1;
  }
  if (nameA > nameB) {
    return 1;
  }

  // names must be equal
  return 0;
});
therealdakotal
  • 244
  • 1
  • 11