Merging multiple arrays and get an array of common elements as output - arrays

I'm trying to merge several arrays in javascript/typescript in angular, I need to output an array with the common values in all the arrays.
for eg:
arrayOne = [34, 23, 80, 93, 48]
arrayTwo = [48, 29, 10, 79, 23]
arrayThree = [23, 89, 48, 20, 63]
output: outputArr= [23, 48]
for getting common elements out of 2 arrays i'm filtering one array with the element from the next array.
return this.arrayOne.filter(el => this.arrayTwo.includes(el));
How do I do it effectively if I have to combine large number of arrays....?
Thanks in advance...

You could use multiple Set to quickly look up for each value among the different sets.
const intersection = <T>(arrays: T[][]): T[] => {
if (arrays.length == 0) return [];
if (arrays.length == 1) return arrays[0];
const sets = arrays.slice(1).map(array => new Set(array));
const result = [];
arrays[0].forEach(item => {
if (sets.every(set => set.has(item))) {
result.push(item);
}
});
return result;
};
const arrayOne = [34, 23, 80, 93, 48];
const arrayTwo = [48, 29, 10, 79, 23];
const arrayThree = [23, 89, 48, 20, 63];
const result = intersection([arrayOne, arrayTwo, arrayThree]);
console.log(result);

One approach is to create an initial set that contains the first array's elements. Then loop over the other arrays, converting them to sets and updating the initial set to retain the corresponding set intersection.
const commonElements = function(arrays) {
if (arrays.length == 0)
return [];
const intersection = new Set(arrays[0]);
for (const array of arrays) {
const set = new Set(array);
for (x of intersection) {
if (!set.has(x))
intersection.delete(x);
}
}
return Array.from(intersection);
};
Calling this function on the sample arrays in the question:
commonElements([
[34, 23, 80, 93, 48],
[48, 29, 10, 79, 23],
[23, 89, 48, 20, 63]])
Returns:
[23, 48]

Related

How to Search and Replace object property value if each key has an array of numbers? Javascript

Let's say we have an object with an array of numbers for each property:
const obj = {
line1: [2, 13, 7, 6, 14],
line2: [25, 16, 24, 27, 28],
line3: [41, 31, 32, 44, 42],
};
How can we Search for a specific number and Replace it with another number?
Let's say we would like to find number 44 and replace it with 88? In a modern JS way...
You can use loop to iterate on each key-value pair of the object, and then you can find and replace the number you want in the array. Keep in mind that if the number can be more than once in the same array you will have to loop on the array as well, otherwise you can use indexOf and assign the new value.
Here is an example:
const obj = {
line1: [2, 13, 7, 6, 14],
line2: [25, 16, 24, 27, 28],
line3: [41, 31, 32, 44, 42],
};
const changeNumber = (oldNum, newNum, obj) => {
for (const [key, arr] of Object.entries(obj)) {
const index = arr.indexOf(oldNum);
if (index > -1) {
arr[index] = newNum;
}
}
}
console.log(obj); // Before
changeNumber(44, 88, obj);
console.log(obj); // After
/* With duplicates entries */
const changeNumberDuplicate = (oldNum, newNum, obj) => {
for (const [key, arr] of Object.entries(obj)) {
let index = 0;
do {
index = arr.indexOf(oldNum, index);
if (index > -1) {
arr[index] = newNum;
}
} while (index > -1);
}
}
const objDup = {
line1: [2, 13, 44, 6, 44],
line2: [44, 16, 44, 27, 28],
line3: [41, 44, 32, 44, 42],
};
console.log(objDup); // Before
changeNumberDuplicate(44, 88, objDup);
console.log(objDup); // After

How do I add items of multiple arrays with respect to their indexes in dart?

CODE:
void func({String value}) async {
final QuerySnapshot snapshot = await _firestore
.collection('users')
.where("id", isEqualTo: signedInUser.id)
.get();
snapshot.docs.forEach((element) {
List<dynamic> arr = element.data()["array"];
print(arr);
}
}
OUTPUT:
I/flutter (27759): [10, 20, 30, 33, 34, 24]
I/flutter (27759): [2, 42, 45, 23, 85, 51]
I/flutter (27759): [32, 53, 12, 67, 34, 23]
This is what I get when I print the list from Firebase document.
How do I add items of the arrays for each respective indexes? Like; 10 + 2 + 32 for index 0
You should be able to get the List of Lists and then using a for loop sum the data like:
var lists = snapshot.docs.map((e) => e.data()['array']);
var sums = <int>[];
for (int i = 0; i < lists.first.length; i++) {
var sum = 0;
for (var list in lists) {
sum += list[i];
}
sums.add(sum);
}
Be aware that this code is not tested, and you need to make sure that the lists are of equal length or the code might not work as you expect/throw an exception.

How to duplicate array within same array x times?

So, I have made function that return publicKey and I need to duplicate it x times for later use.
For example: publicKey: [76, 152, 93, 102, 145, 181] and I need to duplicate it 3 times, so the end result should be [76, 152, 93, 102, 145, 181, 76, 152, 93, 102, 145, 181, 76, 152, 93, 102, 145, 181].
I have tried using var list3 = publicKey*x, but as you can imagine, it didn't work..
fun getPublicKey(privateKey: ArrayList<BigInteger>,
birthDay: BigInteger,
primNumb: BigInteger): ArrayList<BigInteger> {
val inversMod = birthDay.modInverse(primNumb)
//println(inversMod)
val publicKey: ArrayList<BigInteger> = ArrayList()
for (keyValue in privateKey){
val pagaiduValue = (keyValue * inversMod).mod(primNumb)
//println("($keyValue * $inversMod) mod $primNumb = $pagaiduValue")
publicKey.add(pagaiduValue)
}
return publicKey
}
Here's a short and simple solution:
inline fun <T> Iterable<T>.times(count: Int) = (1..count).flatMap { this }
Can be used like this:
val numbers = listOf(1, 2, 3)
val result = numbers.times(5)
println(result) // [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
Perhaps the naming could use some work, times could also be assumed to have the effect of multiplying each element by a given number, repeat could be a better alternative. Also, you might wanna define it on Array<T> and the primitive array types (IntArray, etc) as well.

How can I sort one array based on another array positions in swift?

In Swift, say I have two arrays:
var array1: [Int] = [100, 40, 10, 50, 30, 20, 90, 70]
var array2: [Int] = [50, 20, 100, 10, 30]
I want to sort my aary1 as per array2
So final output of my array1 will be: // array1 = [50, 20, 100, 10, 30,
40, 90, 70]
Even though your question is quite vaguely worded, judging from your example, what you actually want is the union of the two arrays, with the elements of the smaller array coming in first and after them the unique elements of the bigger array in an unchanged order at the end of this array.
The following code achieves the result of the example:
let combined = array2 + array1.filter{array2.index(of: $0) == nil}
You have not defined how you want the elements in array1 but not in array2 to be sorted. This solution assumes you want to sort those not-found elements by their numeric value:
var array1 = [100, 40, 10, 50, 30, 20, 90, 70]
var array2 = [50, 20, 100, 10, 30]
array1.sort {
let index0 = array2.index(of: $0)
let index1 = array2.index(of: $1)
switch (index0, index1) {
case (nil, nil):
return $0 < $1
case (nil, _):
return false
case (_, nil):
return true
default:
return index0! < index1!
}
}
print(array1) // [50, 20, 100, 10, 30, 40, 70, 90]
// ^ order not defined in array2

splitting an array into subarrays by variables value

I have an array of ages.
I want to split the array in to 4 subarrays by the age value.
A -> 0...25
B -> 26...50
c -> 51...75
d -> 76 +
I have no problem iterating through the array and append to different arrays by the age value.
let subArrays: [[Int]] = [[], [], [], []]
for age in ages {
switch age {
case 0...25:
subArrays[0].append(age)
case 26...50:
subArrays[1].append(age)
case 51...75:
subArrays[2].append(age)
default:
subArrays[3].append(age)
}
}
My questions is:
Is there a cleaner way to do this using map, split or any other function.
Thanks
This doesn't use map or anything fancy but you can easily eliminate the switch:
var subArrays: [[Int]] = [[], [], [], []]
for age in ages {
subArrays[min((age - 1) / 25, 3)].append(age)
}
The use of min ensures all values of 76 and greater go into the last slot.
And to test, with all boundary cases, try:
let ages = [ 50, 67, 75, 76, 25, 12, 26, 51, 99, 45, 0, 120, 16 ]
And then:
print(subArrays)
Gives:
[[25, 12, 0, 16], [50, 26, 45], [67, 75, 51], [76, 99, 120]]
A more generic version that does not depend on any mathematical property of your ranges:
func split<T>(array: [T], ranges: [CountableClosedRange<T>]) -> [[T]] {
var result = Array(repeating: [T](), count: ranges.count)
for element in array {
if let subIndex = ranges.index(where: { $0 ~= element }) {
result[subIndex].append(element)
}
}
return result
}
let ages = [10, 20, 30, 40, 50, 60]
let subarrays = split(array: ages, ranges: [0...25, 26...50, 51...75, 76...Int.max])
Note that it does not check for overlapping ranges.
Based on rmaddy's answer (practically the same) but within one line:
let subs = (0...3).map { sub in ages.filter { sub == min(($0 - 1) / 25, 3) } }

Resources