且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何替换另一个值变化的阵列?

更新时间:2023-11-27 22:26:34

数据:

 让日期= [9,10,11,12,13,14,15,16,17,18]
让进口= [9,12,14,18]
让动物= [狗,猫,虎,羊]

重做:

 让过滤= {dates.map拉链(进口,动物).MAP {$ 0.0次} .indexOf($ 0){.MAP动物[$ 0]}? }

输出:

 打印(阵列)// [狗,,,猫,,虎,,,,羊]

基于FranMowinckel的回答

,但100%的安全。

I have a date array which contains the current day plus 10 days, and I am importing an array from a database. I also have an animal name array. Based on what is imported I want to place the animal name in a filtered array in a filtered array. For example:

  date array: `[9, 10, 11, 12, 13, 14, 15, 16, 17, 18]`
  imported date array from db: [9, 12, 14, 18]
  imported animal name array from db: [dog, cat, tiger, sheep]

This is what I want the filtered animal name to look like

filtered animal name array: [dog, "", "", cat, "", tiger, "", "", "", sheep]

I know the code I provided is wrong, I feel I am approaching this incorretly. How should I do this?

 for(var j = 0; j < self.arrayofweek.count; j++){
                        for(var t = 0; t < self.datesfromdb.count; t++){
                            if(self.date[t] == self.datearray[j]){
                                self.namefiltered[t] = self.tutorname[j]
                                 print("filtered name \(self.namefiltered)")
                            }
                        }
                    }

Data:

let dates = [9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
let imported = [9, 12, 14, 18]
let animals = ["dog", "cat", "tiger", "sheep"]

Reworked:

let filtered = dates.map { zip(imported, animals).map { $0.0 }.indexOf($0).map { animals[$0] } ?? "" }

Output:

print(array) // ["dog", "", "", "cat", "", "tiger", "", "", "", "sheep"]

Based on FranMowinckel's answer, but 100% safe.