Filter an array of dictionaries and change its attributes

filter array of dictionaries using predicate
swift 4 filter array of objects
filter array of dictionary in swift 5
swift reduce array of objects
how to get value from array of dictionary in ios swift 4
swift map array of objects
swift filter dictionary
swift array filter object property

I have an array of dictionaries var songsByLetters = [(key: String, value: [Song])]() and the user has selected a song and he will put it in his favorites. So i will need to change the selected song id isFaved boolean to true.

Before i had and array of song object without the first letters of the song as keys to the new dictionary. And i used to do this when user tapped fav button.

@IBAction func favButtonTapped(_ sender: UIButton) {
   dbSongs.filter({$0.id == selectedSongId}).first?.isFaved = sender.isSelected
}

Now as i have a dictionaries I'm trying to do this but its not just the correct way and i have an error of course.

Cannot convert value of type '()?' to closure result type 'Bool'

songsByLetters.filter{$0.value.filter{$0.id == selectedSongId}.first?.isFaved = sender.isSelected}

I understand the error but i don't know how to filter this dictionary and change the isFaved attribute of that certain song id

Here is the song structure:

[
"H":[
       {
         "id": 2134,
         "name": "Happy Brithday",
         "artist": "Paul Anka",
         "isFaved": false,
         "code": "380dj0a"
       },
       {
         "id": 38304,
         "name": "How can i stop loving you",
         "artist": "Savage Garden",
         "isFaved": false,
         "code": "kkdj0a"
       }
   ]
]

Rather than keeping only the id keep the entire Song.

var selectedSong : Song?

...

self.selectedSong = songsByLetters[indexPath.section].value[indexPath.row]

The most efficient solution is to declare Song as class with reference semantics then you don't need to filter at all

@IBAction func favButtonTapped(_ sender: UIButton) {
    selectedSong?.isFaved = sender.isSelected
}

Note: You are discouraged from using a tuple (your dictionary is actually a tuple) as data source.

Filter a nested array and dictionary, You can try this: let serviceWithPrimaryEmail = services.filter({$0.attributes.[1].​value == "Yes"}) // I used the index 1 because as I see in you  The filter() method creates an array filled with all array elements that pass a test (provided as a function). Note: filter() does not execute the function for array elements without values. Note: filter() does not change the original array.

//First you can filter the object

let filtered = dbSongs.filter({$0.id == selectedSongId}).first

//then remove from list

let index = dbSongs.index { $0.id == filtered.id }

  if let index = index {
        let removed = dbSongs.remove(at: index) // Remove item
  }

//Update details

removed.isFaved = true

//finally insert to list.

dbSongs.insert(removed, at index)

Python : Filter a dictionary by conditions on keys or values , This function iterate over all the key value pairs in dictionary and call the given callback function() on each pair. Items for which callback() function  Python programming language provides filter() function in order to filter given array, list, dictionary or similar iterable struct. filter() function can be used to create iterable by filtering some elements of the given data. Syntax. filter() function has following syntax. FUNCTION is the function name we will use to test given dataset and create a new iterable list.

I guess the following code works

  struct Song {
        let id: Int
        let name: String
        let artist: String
        var isFaved: Bool
        let code: String
    }

    var songsByLetter: [String: [Song]] = ["H" : [Song(id: 2134, name: "Happy Birthday", artist: "Paul Anka", isFaved: false, code: "380dj0a"),Song(id: 38304, name: "How can i stop loving you", artist: "Savage Garden", isFaved: false, code: "kkdj0a")]]



    let selectedSongId = 38304
    var songs = songsByLetter.values.map({$0.filter({$0.id == selectedSongId})})

    if let songByH = songs.first, var song = songByH.first
    {
        song.isFaved = true
        let firstLetter = String(song.name.first ?? "0")
        let index = songsByLetter[firstLetter]?.firstIndex(where: {$0.id == selectedSongId})
        if let index = index
        {
            (songsByLetter[firstLetter])?.remove(at: index)
            songsByLetter[firstLetter]?.insert(song, at: index)
        }
    }

    print(songsByLetter)

How to filter nil values out of the collection types— Swift, For example, let's take a look at the following arrays: First one is nullable, So we need to filter those properties when building a dictionary object We have no need to edit anything except making our struct to support one a  filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

Higher order functions in Swift: Filter, Map, Reduce, flatmap, The map function returns these results in an array. Map on Dictionary: Consider a dictionary with book names as key and the amount of each  In this chapter, we will discuss the various array attributes of NumPy. ndarray.shape. This array attribute returns a tuple consisting of array dimensions. It can also be used to resize the array. Example 1

Swift Guide to Map Filter Reduce, Take a few minutes to learn about Swift map, filter and reduce on Swift collection types such as Array or Dictionary is something that can We also need to make the squares array a var as we are changing it in the loop. Python’s dictionaries are great for creating ad-hoc structures of arbitrary number of items. Sometimes, though, it can be awkward using the dictionary syntax for setting and getting the items. For example, let’s say you have the following data structures:

How to simplify your codebase with map(), reduce(), and filter() in , Well, this is the only one not about map/reduce/filter, but it's so compact that it was hard not The filter() method creates a new array with all elements that pass the test Find and replace a key-value pair in an array of objects. var newArray = array.filter(function(item) { return condition; }); The item argument is a reference to the current element in the array as filter() checks it against the condition. This is useful for accessing properties, in the case of objects. If the current item passes the condition, it gets sent to the new array. Filtering an array of objects

Comments
  • Please put the sample dictionary also
  • First filter the song array by song name (letter), then by id.
  • @vadian this means i need to know the key letter also not only the faved song id to filter this.
  • Yes, this increases the efficiency of the filter operation considerably.
  • Can you please attach the structure of dbSongs
  • Yes it is an NSManagedClass CoreData but the ideas is that the data that i get from the api itself and save it in CoreData is not keyed i'm adding the keys in a new dictionary like this songsByLetters = Dictionary(grouping: dbSongs, by: { String($0.name.trimmingCharacters(in: .whitespaces).first!)}).sorted(by: {$0.0 < $1.0}) to have first letter index in my UITableView same as the iOS contacts so now when changing the isFaved will not persist i will need to edit the songsByLetters value isFaved attribute directly.
  • If Song is a class the value will be changed also in the array as selectedSong and the item in the dictionary point to the same object. And from performance perspective your array of tuples is not very efficient. Keep the original grouped dictionary and create an array var keys = dictionary.keys.sorted(). Use keys as section and get the rows by key. That's a lot faster.
  • Im trying to do it to the songsByLetters dictionary not the dbSongs array the dbSongs i have already did it. But now i changed my array to a dictionary of var songsByLetters = [(key: String, value: [Song])]()