0

I have the following tow arrays:

fetchedProducts = [
    [name:  "productName20", id: 20],
    [name:  "productName3", id: 3],
    [name:  "productName1", id: 1]
]
sortedProducts = [
    [productName1: "1"], // I know the numbers here are string; I need them to be string
    [productName20: "20"],
    [productName3: "3"]
]

Now I need to sort fetchedProducts based on the order of sortedProducts so it would end up looking like the following:

fetchedProducts = [
    [name:  "productName1", id: 1],
    [name:  "productName20", id: 20],
    [name:  "productName3", id: 3]
]
pawello2222
  • 46,897
  • 22
  • 145
  • 209
user12669401
  • 229
  • 4
  • 12
  • This has been asked/answered many times before. Does this solve your issue? https://stackoverflow.com/q/43056807/3141234 – Alexander Jun 29 '20 at 23:05

2 Answers2

2

You can try the following in Swift. Note the dictionaries in Swift are unordered so you have to use arrays for ordered collections:

let fetchedProducts = [
    (name: "productName20", id: 20),
    (name: "productName3", id: 3),
    (name: "productName1", id: 1),
]
let sortedProducts = [
    ("productName1", "1"),
    ("productName20", "20"),
    ("productName3", "3"),
]
let sortedFetchedProducts = sortedProducts
    .compactMap { s in
        fetchedProducts.first(where: { s.1 == String($0.id) })
    }

print(sortedFetchedProducts)
// [(name: "productName1", id: 1), (name: "productName20", id: 20), (name: "productName3", id: 3)]
pawello2222
  • 46,897
  • 22
  • 145
  • 209
  • 1
    I would suggest not reinventing the wheel, there's already several really popular questions on this. I would recommend this answer (of mine, not biased at all ) https://stackoverflow.com/a/43056896/3141234 – Alexander Jun 29 '20 at 23:05
1

JavaScipt realisation:

const fetchedProducts = [
    {name:  "productName20", id: 20},
    {name:  "productName3", id: 3},
    {name:  "productName1", id: 1}
];

const sortedProducts = [
    {productName1: "1"}, // I know the numbers here are string; I need them to be string
    {productName20: "20"},
    {productName3: "3"}
];


const sortProducts = (fetchedProducts, sortedProducts) => {
  // Extract ordered id from the sortedProducts array
  const orderIds = sortedProducts.map(sorted => +Object.values(sorted));
  
  // Find product by sorted id and put into new array
  const sortedFetchedProducts = [];
  orderIds.forEach(id => {
    let product = fetchedProducts.find(item => item.id === id);
    sortedFetchedProducts.push(product);
  });

  return sortedFetchedProducts;
}

const sortedFetchedProducts = sortProducts(fetchedProducts, sortedProducts);
console.log(sortedFetchedProducts);

Output:

[ { name: 'productName1', id: 1 },

{ name: 'productName20', id: 20 },

{ name: 'productName3', id: 3 } ]

Jackkobec
  • 5,889
  • 34
  • 34