Skip to content
Advertisement

sorting strings in an object inside an array [closed]

I’ve been trying to sort string inside an object which is inside an array. By splitting the string into array, I successfully sorted the array. I turn the array back to string afterwards. but later when I printed the result, the object inside the array was the same as before. Here is my code:

 function merge(arr, needed_length){

    for(var i = 0; i < arr.length; i++){
        console.log(arr[i]['A1'].split(', ').sort(function(a, b){
            return b - a;
        }).join(', '));

        console.log(arr[i]);
    }

}

console.log(merge([{A1:'8, 7, 9'}, {A1:'4, 8, 6'}, {A1:'2, 4, 3'}], 5));

and here is the printed result:

9, 8, 7
{ A1: '8, 7, 9' }
8, 6, 4
{ A1: '4, 8, 6' }
4, 3, 2
{ A1: '2, 4, 3' }

Can someone help me to understand why the object doesn’t change? Thank you in advance 🙂

Advertisement

Answer

You need to assign the sorted string back to A1:

function merge(arr){
    for(let obj of arr){
        obj.A1 = obj.A1.split(', ').sort((a, b) => b - a).join(', ');
    }
    return arr;
}

let arr = [{A1:'8, 7, 9'}, {A1:'4, 8, 6'}, {A1:'2, 4, 3'}];
merge(arr);
console.log(arr);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement