I have a Dictionary from which I need to have all keys plus one in an Array.
I thought:
let keysArray = Array(dictionary.keys).append("OneMoreKey")
would work. But it results in: Cannot use mutating member on immutable value: function call returns immutable value.
What is the nicest way to do this?
You can append to the array of keys by doing:
let keysArray = Array(dictionary.keys) + ["OneMoreKey"]
The problem with append is that it is attempting to mutate the non-variable array of keys.
Related
In a Mozilla developer translated Korean lang says 'slice method' returns a new array copied shallowly.
so I tested my code.
var animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
var t = animals.slice(2,4);
console.log(t);
t[0] = 'aaa';
console.log(t);
console.log(animals);
but, If slice method returns shallow array, the animals array should be changed with ['ant', 'bison', 'aaa', 'duck', 'elephant'].
Why is it shallow copy?
slice does not alter the original array.
It returns a shallow copy of elements from the original array.
Elements of the original array are copied into the returned array as follows:
For object references (and not the actual object), slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.
For strings, numbers and booleans (not String, Number and Boolean objects), slice copies the values into the new array. Changes to the string, number or boolean in one array do not affect the other array.
If a new element is added to either array, the other array is not affected.(source)
In your case the the array consists of strings which on slice would return new strings copied to the array thus is a shallow copy.
In order to avoid this use the object form of array.
strings are primitive types in JavaScript, so you will get a new array with new strings inside.
Your test array should be an array of objects:
var animals = [{name: 'ant'}, {name: 'bison'}, {name: 'camel'}, {name: 'duck'}, {name: 'elephant'}];
var t = animals.slice(2,4);
console.log(t);
t[0].name = 'aaa';
console.log(t);
console.log(animals);
The slice method doesn't change the original array or string. It only cuts a portion of the original string or array and returns it as a copy.
For more understanding of it, kindly check this video below:
https://youtu.be/mUH8hPQfMbg [Slice method made easy for absolute beginners]
May be you are looking for this. Try this!
let animals = ['ant', 'bison', 'camel', [1, 2]];
let t = animals.slice();
t[0] = 'aaa'; // string (primitive datatype)
t[t.length-1][0] = 0; // array (object)
console.log(t);
console.log(animals);
In case of a shallow copy-
Objects will reflect change in the original place from where they were shallowly copied because they are stored as references (to their address in the Heap).
Primitive data types will NOT reflect change in the original place because they are directly stored in the callstack (in Execution Contexts).
I am using splice to add elements to an array at specified index.However In order to to do so I have to create a null array to add the elements at particular index.
If I use an empty array,the elements are not being pushed at specific instance.Right now i'm creating an empty array and then pushing null to that array.I want to know if I can achieve this with any other way.
This is what I'm doing:
arr:any[];
for(let i=0;i<userDefinedLength;i++)
{
arr.push(null);
}
You can use arr = new Array(userDefinedLength).fill(null);
Use fill:
arr: any[] = new Array(userDefinedLength).fill(null);
You can't use null[] unless you're just using the array as a placeholder:
arr: null[] = new Array(userDefinedLength).fill(null);
let nameArray = ["ramesh","suresh","rajesh"]
let idArray = ["100","101","102"]
Now i want value of "idArray" by using index value of "nameArray".
if nameArray index is 0. Output is 100
In Object Oriented Programming, objects should own their properties. So instead of having two data structures describe the same object, either use structs like Mr. Vadian has suggested, or have one array store all the properties of the objects:
let zippedArray = Array(zip(nameArray, idArray))
And now to get the object in a given index, you can use the following:
let index = 0
let element = zippedArray[0]
print(element.0) //ramesh
print(element.1) //100
I have an dictionary that I want to iterate trough in a tableview. One way of doing this is to create an array with all the keys and just fetch the key at the given index. But for this array I want the keys to be ordered alphabetically by the values in the dictionary. How do I do this?
static let dict = [
"0P0000KBNA": "Länsförsäkringar Europa Indexnära",
"0P0000YVZ3": "Länsförsäkringar Global Indexnära",
"0P0000J1JM": "Länsförsäkringar Sverige Indexnära",
"0P00013668": "Länsförsäkringar Tillväxtmarknad Indexnära A",
"0P0000K9E7": "Länsförsäkringar USA Indexnära",
"0P00005U1J": "Avanza Zero"
]
static let sortedKeys = Array(dict.keys) // How?
You just need to sort your dictionary by value and map the key
let sortedKeys = dict.sorted{$0.value < $1.value}.map{$0.key} // ["0P00005U1J", "0P0000KBNA", "0P0000YVZ3", "0P0000J1JM", "0P00013668", "0P0000K9E7"]
As a minor variation of #LeoDabus answer, you could access the keys property of your dictionary and sort this array according to the corresponding value for each key
let sortedKeys = dict.keys.sorted { dict[$0]! < dict[$1]! }
print(sortedKeys)
/* ["0P00005U1J",
"0P0000KBNA",
"0P0000YVZ3",
"0P0000J1JM",
"0P00013668",
"0P0000K9E7"] */
Note also that the forced unwrapping operator ! is generally to be avoided, but in this particular case, we know that both shorthand arguments $0 and $1 in the predicate closure supplied to sorted(...) are guaranteed to be valid keys in the dictionary (since your dictionary is immutable: so no asynch risks here).
First, make a new array of strings called keysArray.
Second, loop over your array of dictionaries and add all the keys to the newly created array.
Now keysArray should be an array of the keys.
Third, sort sortedKeysArray as follow
var sortedArray = sortedKeysArray.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending}
Now we have an array of the sorted Keys.
After this if you need to have an array of the dictionaries, create a new array called sortedDictArray. Then loop over sortedKeysArray we made previously and get the dictionary by key and add it to sortedDictArray. Viola!
Hope this helps you!
Ordered Dictionary
I've used the open source OrderedDictionary created by Lukas Kubanek to solve problems like this.
For the usage of this library you can refer to the example playground.
This question already has answers here:
Get an array of property values from an object array
(2 answers)
Closed 6 years ago.
I get an element from a collection with this code:
modelCollec[indexPath].model
I want to get all models in an array. Is there a function or shall I write a loop?
There is only one row so indexPath is always [0, index].
Use flatMap for that.
let modelArray = modelCollec.flatMap { $0.model }
modelArray type is [model].
For eg:
struct Person {
var name: String
}
Now if you have array of person and you want array of name from it you can get it using flatMap like this way.
let persons = [Person]()
let nameArray = persons.flatMap { $0.name } //nameArray type is [String]
Note: You can also use map instead of flatMap but it will give you optional objects if your model property is optional so it may contains nil where as flatMap ignore the nil object.
If you always want to access the 1st element of the collection then it is a better idea to hardcode the 0 index rather than using loop, however to it is always better to put a check for nil.