0
\$\begingroup\$

I have to sort the array based on rating in a specific pattern.

3 star = 5, 4star = 3 , 5 star =7

[3 star hotel, 4 star hotel, 5 star hotel]

Note: Replace 3 star hotel with 4 star hotel if 4 star are not there.

expected pattern: 345 345 345 335 555

basically i want to sort some hotels based on rating

inputs :

3* = 5 (number of 3 star hotels is 5)

4* = 3 (number of 4 star hotels is 3)

5* = 4 (number of 5 star hotels is 4)

{
    3: ["3","3","3","3","3"],
    4: ["4", "4", "4"],
    5: ["5", "5", "5", "5"]
}

output:

enter image description here

can anyone know how can we achieve the solution in a better way?

my current implementation is

function getMaxLength(hotelRating) {
    return Math.max(hotelRating[3].length, hotelRating[4].length, hotelRating[5].length);
}

function getOrderedHotelRating(hotelRating) {
    const orderedHotelRatingArr = [];
    const unorderedHotelRatingArr = [];
    const modifiedHotelRatingArr = [];
    const unorderedHotelRatingObj = {
        3: [],
        4: [],
        5: []
    };
    for (let i = 0; i < getMaxLength(hotelRating); i++) {
        if (hotelRating[3][i] && hotelRating[4][i] && hotelRating[5][i]) {
            orderedHotelRatingArr.push([hotelRating[3][i], hotelRating[4][i], hotelRating[5][i]]);
        } else {
            unorderedHotelRatingArr.push([hotelRating[3][i] || 0, hotelRating[4][i] || 0, hotelRating[5][i] || 0]);
        }
    }

    unorderedHotelRatingArr.forEach(ar=>{
        if (ar[0]) {
            unorderedHotelRatingObj[3].push(ar[0]);
        }
        if (ar[1]) {
            unorderedHotelRatingObj[4].push(ar[1]);
        }
        if (ar[2]) {
            unorderedHotelRatingObj[5].push(ar[2]);
        }
    });

    [...unorderedHotelRatingObj[3], ...unorderedHotelRatingObj[4], ...unorderedHotelRatingObj[5]].forEach((ar,index,list)=>{
        // console.log(index)
        if (index % 3 === 0) {
            modifiedHotelRatingArr.push(list.slice(index, index + 3));
        }
    }
    );
    return [...orderedHotelRatingArr, ...modifiedHotelRatingArr];
}

let result = getOrderedHotelRating({
    3: ["3","3","3","3","3"],
    4: ["4", "4", "4"],
    5: ["5", "5", "5", "5"]
});
console.log(result);

\$\endgroup\$
1
  • \$\begingroup\$ What exactly do you want to improve? Performance, shorten the code? \$\endgroup\$
    – pacmaninbw
    Oct 12, 2021 at 20:45

0

Browse other questions tagged or ask your own question.