根据另一个数组Swift的顺序对数组进行排序

时间:2020-06-29 20:49:01

标签: arrays swift sorting arraylist

我有以下两个拖车阵列:

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

现在我需要根据fetchedProducts的顺序对sortedProducts进行排序,这样最终结果将如下所示:

fetchedProducts = [
    [name:  "productName1", id: 1],
    [name:  "productName20", id: 20],
    [name:  "productName3", id: 3]
]

2 个答案:

答案 0 :(得分:1)

JavaScipt实现:

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);

输出:

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

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

{名称:'productName3',ID:3} ]

答案 1 :(得分:1)

您可以在Swift中尝试以下方法。请注意,Swift中的字典是无序的,因此您必须对有序集合使用数组:

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)]
相关问题