Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to reorder this array without an index?

Let say I have

let arr = [
{code: 5, country: 'DE', price: 8},
{code: 6, country: 'RU', price: 9},
{code: 7, country: 'US', price: 10},
{code: "FiveX", country: 'UK', price: 11},
{code: 5, country: 'ES', price: 12},
{code: 5, country: 'RU', price: 13},
{code: 7, country: 'BE', price: 14},
]

I need this array to be reordered as follows

arr = [
{priceDE: '8 (code5)' , priceES: '12 (code5)', priceRU: '13 (code5)'},
{priceRU: '9 (code6)'},
{priceUS: '10 (code7)', priceBE: '14 (code7)'}
{priceUK: '11 (codeFiveX)'}
]

I basically need to group them with the code reference, but I dont really understand how to do it without knowing the value of code beforehand. Keep in mind that code isn’t always a number it can be a string

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

First of all your original array declaration is wrong, as it uses DE as a variable while it should be a string encapsulated by quotes 'DE' so you need to rewrite that to be reproducible.

So for example {code: 5, country: 'DE', price: 8},

Then you need to loop your original array, take the values and rebuild a new object with the new values. I say object and not array since we need to use a key that in your case can be either a number, e.g. 5, or a string, e.g. FiveX.

Here’s the resulting snippet

let arr = [
{code: 5, country: 'DE', price: 8},
{code: 6, country: 'RU', price: 9},
{code: 7, country: 'US', price: 10},
{code: "FiveX", country: 'UK', price: 11},
{code: 5, country: 'ES', price: 12},
{code: 5, country: 'RU', price: 13},
{code: 7, country: 'BE', price: 14},
]

let new_arr = {}
for(i=0; i<arr.length; i++) {
    let code = arr[i].code
    let country = arr[i].country
    let price = arr[i].price
    if (code in new_arr) {
        new_arr[code]['price'+country] = price
    } else {
        new_arr[code] = {}
        new_arr[code]['price'+country] = price
    }
}
console.log(new_arr)

The resulting array will be what you requested, apart from the weird (code5) which if you want you can add by concatenating price+" (code"+code+")" in the for loop.

EDIT

I forgot, if you want the final item to be an array instead of an object, you can loop it again.

let final_arr = []
for(i in new_arr) {
    final_arr.push(new_arr[i])
}
console.log(final_arr)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading