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]
]
1

2 Answers 2

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)]
Sign up to request clarification or add additional context in comments.

1 Comment

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 😉) stackoverflow.com/a/43056896/3141234
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 } ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.