how to get array value by using index value of another value? - arrays

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

Related

How to use contains method on a 2D array in scala

I have a 2d array and I want to check whether an array exists inside the 2d array.
I have tried:
var arr = Array(Array(2,1), Array(4,3))
var contain = arr.contains(Array(4, 3))
println(contain)
This should print true but it doesn't work.
Method contains doesn't work because it uses equals to determine equality and for arrays equals is using reference equality, so it will return true only for two references pointing the same object.
You could use find + sameElements:
var arr = Array(Array(2,1), Array(4,3))
var contain = arr.find(_.sameElements(Array(4, 3))).isDefined
println(contain)
Consider using ArrayBuffer instead of Array, if you need mutable collection, like so
val arr = ArrayBuffer(ArrayBuffer(2,1), ArrayBuffer(4,3))
val contain = arr.contains(ArrayBuffer(4, 3))
println(contain)
which outputs
true
Also consider question What is the difference between ArrayBuffer and Array
A more elegant solution would be the following
val array = Array(Array(2,1), Array(4,3))
val result = array.exists(_.sameElements(Array(4, 3)))
println(result)
Output
true

How to append to newly initialized Array() in single expression?

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.

Store value in an array

I am fairly new to Go. I have coded in JavaScript where I could do this:
var x = [];
x[0] = 1;
This would work fine. But in Go, I am trying to implement the same thing with Go syntax. But that doesn't help. I need to have a array with unspecified index number.
I did this:
var x []string
x[0] = "name"
How do I accomplish that?
When you type:
var x []string
You create a slice, which is similar to an array in Javascript. But unlike Javascript, a slice has a set length and capacity. In this case, you get a nil slice which has the length and capacity of 0.
A few examples of how you can do it:
x := []string{"name"} // Creates a slice with length 1
y := make([]string, 10) // Creates a slice with length 10
y[0] = "name" // Set the first index to "name". The remaining 9 will be ""
var z []string // Create an empty nil slice
z = append(z, "name") // Appends "name" to the slice, creating a new slice if required
More indepth reading about slices:
Go slices usage and internals
In JavaScript arrays are dynamic in the sense that if you set the element of an array using an index which is greater than or equal to its length (current number of elements), the array will be automatically extended to have the required size to set the element (so the index you use will become the array's new length).
Arrays and slices in Go are not that dynamic. When setting elements of an array or slice, you use an index expression to designate the element you want to set. In Go you can only use index values that are in range, which means the index value must be 0 <= index < length.
In your code:
var x []string
x[0] = "name"
The first line declares a variable named x of type []string. This is a slice, and its value will be nil (the zero value of all slice types, because you did not provide an initialization value). It will have a length of 0, so the index value 0 is out of range as it is not less that the length.
If you know the length in advance, create your array or slice with that, e.g.:
var arr [3]string // An array with length of 3
var sli = make([]string, 3) // A slice with length of 3
After the above declarations, you can refer to (read or write) values at indicies 0, 1, and 2.
You may also use a composite literal to create and initialize the array or slice in one step, e.g.
var arr = [3]string{"one", "two", "three"} // Array
var sli = []string{"one", "two", "three"} // Slice
You can also use the builtin append() function to add a new element to the end of a slice. The append() function allocates a new, bigger array/slice under the hood if needed. You also need to assign the return value of append():
var x []string
x = append(x, "name")
If you want dynamic "arrays" similar to arrays of JavaScript, the map is a similar construct:
var x = map[int]string{}
x[0] = "name"
(But a map also needs initialization, in the above example I used a composite literal, but we could have also written var x = make(map[int]string).)
You may assign values to keys without having to declare the intent in prior. But know that maps are not slices or arrays, maps typically not hold values for contiguous ranges of index keys (but may do so), and maps do not maintain key or insertion order. See Why can't Go iterate maps in insertion order? for details.
Must read blog post about arrays and slices: Go Slices: usage and internals
Recommended questions / answers for a better understanding:
Why have arrays in Go?
How do I initialize an array without using a for loop in Go?
How do I find the size of the array in go
Keyed items in golang array initialization
Are golang slices pass by value?
Can you please use var x [length]string; (where length is size of the array you want) instead of var x []string; ?
In Go defining a variable like var x=[]int creates a slice of type integer. Slices are dynamic and when you want to add an integer to the slice, you have to append it like x = append(x, 1) (or x = append(x, 2, 3, 4) for multiple).
As srxf mentioned, have you done the Go tour? There is a page about slices.
I found out that the way to do it is through a dynamic array. Like this
type mytype struct {
a string
}
func main() {
a := []mytype{mytype{"name1"}}
a = append(a, mytype{"name 2"})
fmt.Println(a);
}
golang playground link: https://play.golang.org/p/owPHdQ6Y6e

Filter values of Array<String> from another Array<String>

I have two arrays:
let arr1 = ["one.json", "two.json", "three.json"]
let arr2 = ["one.json", "three.json"]
Now I want to remove all values of arr2 in arr1, so my expected result in the example above would be let arrFiltered = ["two.json"]. I know how to handle this using a for-loop, however, I thought there may is an easier and more performance-oriented solution?
You have to use Set instead of Array in this case.
let arr1 = Set(["one.json", "two.json", "three.json"])
let arr2 = Set(["one.json", "three.json"])
arr1.subtract(arr2)
Fundamental Set Operations
The illustration below depicts two sets–a and b– with the results of
various set operations represented by the shaded regions.
Use the intersect(_:) method to create a new set with only the values common to both sets.
Use the exclusiveOr(_:) method to create a new set with values in either set, but not both.
Use the union(_:) method to create a new set with all of the values in both sets.
Use the subtract(_:) method to create a new set with values not in the specified set.
Read more
Solution using the filter function
let arr1 = ["one.json", "two.json", "three.json"]
let arr2 = ["one.json", "three.json"]
let arrFiltered = arr1.filter{ !arr2.contains($0) }

Is it possible to append a new object to a heterogenous array in swift?

I know that true mutability can not be achieved in swift. I have an array interspersed with different types of contents.
let myArray = String[]();
var array = ["First","Second","Third",1,0.4,myArray,"dsaa"]
I learned from the above post I have linked that we will be able to append items to an array. But each time I add a new item to the array I have declared above I get this error:
could not find an overload for '+=' that accepts the supplied
arguments
But when the array is homogeneous, I am able to add an item which is same as the already present items, without hassle. but still the item with a different type can not be added.
If you declare your second array explicitly as AnyObject[], you can do it:
let myArray = String[]()
var array:AnyObject[] = ["First", "Second", "Third", 1, 0.4, myArray, "dsaa"]
let n1 = array.count // 7
array += "next"
let n2 = array.count // 8

Resources