I do have two arrays
arr1 = [1,2,3,4] //readonly array
arr2 = [1,2,3,4,5,6,7]
arr1 is the main array and I want to update it with contents from arr2 so that when i log arr1 it will display
[1,2,3,4,5,6,7]
is there a way I can do this
let arr1 = [1,2,3,4];
let arr2 = [1,2,3,4,5,6,7];
arr1 = [...new Set([...arr1 ,...arr2])];
console.log(arr1); // [1,2,3,4,5,6,7]
var mergedArray = new Array(...arr1, arr2) // [1,2,3,4,1,2,3,4,5,6,7]
var finalArray = []
mergedArray.forEach(item => {
if (!finalArray.includes(element)) {
finalArray.push(element);
}
})
console.log(finalArray) // [1,2,3,4,5,6,7]
mergedArray will be a new array that we create by merging both arr1 and arr2. Then we check for unique elements in mergedArray by using the forEach method and add non-repeating elements to finalArray.
Related
i have two arrays like these
var arr1 = ["han", "Ji", "Kidda", "Ho", "Tusi"]
var arr2 = ["hello", "Ji"]
i want to create a new dictionary that have first element of first array and first element of second array and so on. when the third element of first array comes it should again get the first element of second array.
for example:-
dict = ["han" : "hello", "Ji" : "Ji", "Kidda" : hello, "Ho" : "Ji", "Tusi" : "hello"]
If the second array has 2 items you can do
var dict = [String: String]()
for (index, item) in arr1.enumerated() {
dict[item] = arr2[index % 2]
}
I believe this is what you're looking for (using arr1 as the keys and arr2 as the values repeating them as necessary):
var arr1 = ["han", "Ji", "Kidda", "Ho", "Tusi"]
var arr2 = ["hello", "Ji"]
let dict = Dictionary(uniqueKeysWithValues: zip(arr1, arr1.indices.map { arr2[$0 % arr2.count] }))
print(dict)
["Kidda": "hello", "Ji": "Ji", "han": "hello", "Ho": "Ji", "Tusi": "hello"]
Note:
Dictionaries have no specified ordering. Only the key/value pairings matter. This matches the example in your question.
Explanation:
zip is used to create a sequence of (key, value) tuples from two sequences that will become the key/value pairs for the new Dictionary. The keys come from arr1. map is used to generate the sequence of values from arr2 repeating them as many times as necessary to match the count of arr1. This sequence of (key, value) tuples is passed to Dictionary(uniqueKeysWithValues:) to turn that sequence into the desired Dictionary.
try:
var dict = ["arr1" : "hello", "arr2" : "Ji"]
then for third you can append by
dict[3] = ["arr3" : String(arr3.first())]
Try this:
var arr1 = ["han", "Ji", "Kidda", "Ho", "Tusi"]
var arr2 = ["hello", "Ji"]
var dict : [String : String] = [:]
var arr2Index = 0
for index in 0..<arr1.count {
let arr1Value = arr1[index]
if arr2Index == arr2.count {
arr2Index = 0
}
let arr2Value = arr2[arr2Index]
dict[arr1Value] = arr2Value
arr2Index += 1
}
Here's a fun way:
let arr1 = ["han", "Ji", "Kidda", "Ho", "Tusi"]
let arr2 = ["hello", "Ji"]
let arr3 = Array(repeating: arr2, count: arr1.count).joined()
let d = zip(arr1,arr3).reduce(into: [String:String]()) { $0[$1.0] = $1.1 }
I have an array in javascript shown below
var multiArray = [['Jan',12],['Feb',13],['Mar',14]];
Now i want the elements of the above array elements into two seperate arrays as
var array1 = ['Jan','Feb','Mar'];
var array2 = [12,13,14];
Which methodology should i use to convert them as separate arrays.?
You could use a Map to convert them
const multiArray = [['Jan',12],['Feb',13],['Mar',14]];
const m = new Map(multiArray);
const arr1 = Array.from(m.keys());
const arr2 = Array.from(m.values());
console.log(arr1, arr2);
In your case this is the easiest approach:
var multiArray = [['Jan',12],['Feb',13],['Mar',14]];
var arr1 = multiArray.map(x => x[0])
var arr2 = multiArray.map(x => x[1])
I have an array array1 = [1,2,3,4,5,6] and another array array2 = [4,5].
The objective is to remove array2's elements from array1 with the least time complexity.
Final array is [1,2,3,6]
I know we can do something like this for every element
function remove(array, element) {
return array.filter(e => e !== element);
}
let array1 = [1,2,3,4,5,6];
array2 = [4,5];
array2.forEach(el => {
array1 = remove(array1, el);
});
How do i make it better?
I have two solutions for you :
var arr1 = [ 1, 2,3 ];
var arr2 = [1,2,4 ];
var result = arr1.filter(o1 => arr2.filter(o2 => o2 === o1).length === 0);
console.log(result);
Or you can use difference of Loadash
Simpler and cleaner
const arr1 = [1,2,3,4]
const arr2 = [3,4]
const newArray = arr1.filter( x => !arr2.includes(x))
console.log(newArray)
I tested in Swift 3.0. I want to add array1 to array2, example and errors as below:
var array1: [String?] = ["good", "bad"]
var array2 = [String!]()
array2.append(array1)
//Cannot convert value of type '[String?]' to expected argument type 'String!'
array2.append(contentsOf: array1)
//Extraneous argument label 'contentsOf:'in call
I know if I change to
var array2 = [String?]()
array2.append(contentsOf: array1)
it works!
How should I fix this if i don't change type?
In Swift 3 you cannot define an array where the generic element is an implicitly unwrapped optional.
Implicitly unwrapped optionals are only allowed at top level and as function results.
The compiler
What you can do is creating a new array of String containing only the populated elements of array1.
let array1: [String?] = ["good", "bad", nil]
let array2: [String] = array1.flatMap { $0 }
print(array2) // ["good", "bad"]
Update
As shown by Sam M this is indeed possible, here's the code
let array2 = array1.map { elm -> String! in
let res: String! = elm
return res
}
var array1: [String?] = ["good", "bad"]
var array2 = [String!]()
var array2a = [String]()
for item in array1 {
array2.append(item)
}
for item in array1 {
array2a.append(item!)
}
print("1", array1)
print("2", array2)
print("2a", array2a)
Prints:
1 [Optional("good"), Optional("bad")]
2 [good, bad]
2a ["good", "bad"]
Mapping also works, e.g.:
array2 = array1.map{ $0 }
array2a = array1.filter{ $0 != nil }.map{ $0! }
Is there a cleaner way to get the last two items of an array in Swift? In general, I try to avoid this approach since it's so easy to be off-by-one with the indexes. (Using Swift 1.2 for this example.)
// Swift -- slices are kind of a hassle?
let oneArray = ["uno"]
let twoArray = ["uno", "dos"]
let threeArray = ["uno", "dos", "tres"]
func getLastTwo(array: [String]) -> [String] {
if array.count <= 1 {
return array
} else {
let slice: ArraySlice<String> = array[array.endIndex-2..<array.endIndex]
var lastTwo: Array<String> = Array(slice)
return lastTwo
}
}
getLastTwo(oneArray) // ["uno"]
getLastTwo(twoArray) // ["uno", "dos"]
getLastTwo(threeArray) // ["dos", "tres"]
I was hoping for something closer to Python's convenience.
## Python -- very convenient slices
myList = ["uno", "dos", "tres"]
print myList[-2:] # ["dos", "tres"]
With Swift 5, according to your needs, you may choose one of the following patterns in order to get a new array from the last two elements of an array.
#1. Using Array's suffix(_:)
With Swift, objects that conform to Collection protocol have a suffix(_:) method. Array's suffix(_:) has the following declaration:
func suffix(_ maxLength: Int) -> ArraySlice<Element>
Returns a subsequence, up to the given maximum length, containing the final elements of the collection.
Usage:
let array = [1, 2, 3, 4]
let arraySlice = array.suffix(2)
let newArray = Array(arraySlice)
print(newArray) // prints: [3, 4]
#2. Using Array's subscript(_:)
As an alternative to suffix(_:) method, you may use Array's subscript(_:) subscript:
let array = [1, 2, 3, 4]
let range = array.index(array.endIndex, offsetBy: -2) ..< array.endIndex
//let range = array.index(array.endIndex, offsetBy: -2)... // also works
let arraySlice = array[range]
let newArray = Array(arraySlice)
print(newArray) // prints: [3, 4]
myList[-2:]
Yes, I have an enhancement request filed asking for negative index notation, and I suggest you file one too.
However, you shouldn't make this harder on yourself than you have to. The built-in global suffix function does exactly what you're after:
let oneArray = ["uno"]
let twoArray = ["uno", "dos"]
let threeArray = ["uno", "dos", "tres"]
let arr1 = suffix(oneArray,2) // ["uno"]
let arr2 = suffix(twoArray,2) // ["uno", "dos"]
let arr3 = suffix(threeArray,2) // ["dos", "tres"]
The result is a slice, but you can coerce it to an Array if you need to.
in swift 5 you can use suffix for get objects from the last and use prefix for get objects from the first, here is an example:
let exampleArray = ["first text", "second text", "third text"]
let arr1 = exampleArray.suffix(2) // ["second text", "third text"]
let arr2 = exampleArray.prefix(2) // ["first text", "second text"]
The result is a slice, but you can coerce it to an Array if you need to.
In Swift 2, you can extend CollectionType. Here's an example (borrowing from Rob Napier's answer):
extension CollectionType {
func last(count:Int) -> [Self.Generator.Element] {
let selfCount = self.count as! Int
if selfCount <= count - 1 {
return Array(self)
} else {
return Array(self.reverse()[0...count - 1].reverse())
}
}
}
You can use it on any CollectionType. Here's Array:
let array = ["uno", "dos", "tres"]
print(array.last(2)) // [dos, tres]
Here's CharacterView:
let string = "looking"
print(string.characters.last(4)) // [k, i, n, g]
(Note that my example returns an Array in all cases, not the original collection type.)
More generic answer ...
let a1 = [1,2,3,4,5]
let a2 = ["1","2","3","4","5"]
func getLast<T>(array: [T], count: Int) -> [T] {
if count >= array.count {
return array
}
let first = array.count - count
return Array(array[first..<first+count])
}
getLast(a1, count: 2) // [4, 5]
getLast(a2, count: 3) // ["3", "4", "5"]
the last two items of an array in Swift
EDIT: first checks that myArray.count >= 2
let myArray2:Array? = myArray.count >= 2 ? [myArray[myArray.count-2], myArray[myArray.count-1]] : nil
Here it is wrapped in a function which takes the array and either returns an array containing the last two or else returns nil if the passed array does not contain at least two items.
func getLastTwo(myArray:[String]) -> [String]? {
return myArray.count >= 2 ? [myArray[myArray.count-2], myArray[myArray.count-1]] : nil
}
I doubt it's going to make you that much happier, but the math is certainly simpler:
func getLastTwo(array: [String]) -> [String] {
if array.count <= 1 {
return array
} else {
return array.reverse()[0...1].reverse()
}
}
Note that reverse() is lazy, so this isn't particularly expensive.
let items = [0, 2, 5, 3, 7, 6, 9, 10]
let count = items.count
let last2 = items[count - 2 ..< count] // [9, 10]
Swift4 solution:
let oneArray = ["uno"]
let twoArray = ["uno", "dos"]
let threeArray = ["uno", "dos", "tres"]
let arr1 = threeArray.suffix(from: threeArray.count-2) // ["dos", "tres"]
Other examples to clarify the functionality of Swift's built in function func suffix(from start: Int) -> ArraySlice<Element> are...
let arr2 = oneArray.suffix(from: 0) // ["uno"]
let arr3 = twoArray.suffix(from: 0) // ["uno", "dos"]
let arr4 = twoArray.suffix(from: 1) // ["dos"]
let arr5 = threeArray.suffix(from: 1) // ["dos", "tres"]
let arr6 = threeArray.suffix(from: 2) // ["tres"]