Math with typescript array - Angular - arrays

I'm really confused about how to approach this:
I have an array like this:
arr=["X12","Z1","Y7","Z22","X4","X8"]
I wish to perform mathematical functions on the elements such that:
Each element starting with "X" will have a fixed value 5, hence if there are 3 elements starting with "X" inside the array arr, it should go as : (fixed value of X) multiplied by (No. of "X" element occurrences inside array) = 5x3 = 15.
I tried something like this to calculate the no. of occurrences of "X" element but it doesn't work.
var xcounter = 0;
calculate(){
this.arr.forEach(element => {
if(this.arr.includes("X"))
{
this.xcounter++; //this doesn't give me no. of X element occurrences though.
}
});
}
What would be a clutter-free way to do this?

You could try to use array filter() with string startsWith() method.
var arr = ["X12","Z1","Y7","Z22","X4","X8"];
var valueX = 5;
var occurencesX = arr.filter(item => item.startsWith('X')).length;
console.log(occurencesX * valueX);

You can also try this
loop in to your array
Find how many time you found values which has X in starts
var arr=["X12","Z1","Y7","Z22","X4","X8"]
let total = 0
arr.forEach(
(row) =>{
total = row.startsWith('X')? total + 1 : total
}
)
console.log(total * 5)

Related

How do I combine numbers in array in Swift?

I am not trying to add the arrays like all the other questions. This is what I want to do:
var a = [1,2,3]
var b = [4,5,6]
var outPut = [14,25,36]
As you can see I want to combine the indexes. How would I do that?
You can zip the two collections, and map the tuple elements multiplying the first element by 10 and adding the second. Of course this assumes your collection of integers are limited to a single digit:
let outPut = zip(a,b).map{ $0 * 10 + $1 } // [14,25,36]
If your collection elements are not limited to a single digit you can multiply the first element by 10 powered by the number of digits of the second collection (this considers that all integers are not negative:
var a = [12,25,37]
var b = [34,567,6443]
let outPut = zip(a,b).map{ $0 * Int(pow(Double(10),Double(String($1).count))) + $1 } // [1234, 25567, 376443]

Execute a special for loop

I have a array:
let array = [1,2,3,4,5]
I need to perform a for loop on this array where at each number I need to add +90, and -90
now here the issue:
in a normal for loop the code will be like this:
for i in array {
let plus = i + 90
append.newArray(plus)
let minus = i - 90
append.newArray(plus)
}
I need to switch the plus and minus..
at the first cycle I need to append to the newArray plus and minus..... but for the second cycle I must append in order minus and plus.
is there any way to switch the for loop to alternate between the plus and minus -- minus plus.
You need to use it, as I understand, for odd and even values in source array, so you can use something like this:
let array = [1, 2, 3, 4, 5]
var newArray: [Int] = []
func plusValue(_ value: Int) {
let plus = value + 90
newArray.append(plus)
}
func minusValue(_ value: Int) {
let minus = value - 90
newArray.append(minus)
}
for (value, index) in array.enumerated() {
if index.isMultiple(of: 2) { // even
minusValue(value)
plusValue(value)
} else { // odd
plusValue(value)
minusValue(value)
}
}
Just need to understand what you need to use for even and for odd indexies.
Here is one way to do it using a for loop over the indices
let array = [1,2,3,4,5]
var output = [Int]()
for index in array.indices {
let value = index % 2 == 0 ? 90 : -90
output.append(array[index] + value)
output.append(array[index] - value)
}
another option is to use reduce(into:)
let output = array.enumerated().reduce(into: []) {
let factor = $1.offset % 2 == 0 ? 1 : -1
$0.append(contentsOf: [$1.element + factor * 90, $1.element - factor * 90])
}

Swift: Excluding a specific index from an array when filtering

I'd like to filter an array of numbers and use reduce on them, but I need to exclude a specific index and I can't divide. Is it possible to do this with methods that are part of Foundation in Swift?
I've tried breaking the array into two using prefix & suffix, but there are some edge cases where it blows up w/ an out of bounds exception.
while currentIndex < nums.count - 2 {
for _ in nums {
let prefix = nums.prefix(currentIndex)
let suffix = nums.suffix(from: currentIndex + 1)
if prefix.contains(0) || suffix.contains(0) {
incrementIndex(andAppend: 0)
}
let product = Array(prefix + suffix).reduce(1, *)
incrementIndex(andAppend: product)
}
}
You can use enumerated() to convert a sequence(eg. Arrays) to a sequence of tuples with an integer counter and element paired together
var a = [1,2,3,4,5,6,7]
var c = 1
let value = a.enumerated().reduce(1) { (_, arg1) -> Int in
let (index, element) = arg1
c = index != 2 ? c*element : c
return c
}
print(value) // prints 1680 i.e. excluding index 2
I'm seeking to figure out how to exclude a specific index
What about this sort of thing?
var nums2 = nums
nums2.remove(at:[currentIndex])
let whatever = nums2.reduce // ...
Where remove(at:) is defined here: https://stackoverflow.com/a/26308410/341994

Compare Array with up to 100 item id's (containing duplicates) to array with unique id's

I want to count how many times numbers from arr1 appear in arr2. I tried intersects with sets however I do not wish to remove duplicates.
var arr1 = [1,4,5,7]
func compareCount(arr2[Int])-> Int {
//arr2 = 1,1,4,5,6,6,3,9,7,7,7,1,7
return count
//returns 9 as there are 9 elements within arr2 that exist within arr1
}
You can use NSCountedSet for that:
var arr1 = [1,4,5,7]
var arr2 = [1,1,4,5,6,6,3,9,7,7,7,1,7]
let countedSet = NSCountedSet(array: arr2)
Then, iterate through arr1 and for each, you'll get easily the number of occurences with count(for:), and with reduce, you can add them:
let numberOfOccurences = arr1.reduce(into: 0) { (result, current) in
let numberOfOccurencesForCurrent = countedSet.count(for: current)
result += numberOfOccurencesForCurrent
}
print("numberOfOccurences: \(numberOfOccurences)")
Edit:
If you don't want to use reduce() (because you want to avoid using it without understanding it), but rather do a more simple loop:
var numberOfOccurences = 0
arr1.forEach({ numberOfOccurences += countedSet.count(for: $0) })
Loop the first array and count every filtered elements in the second one
var count = 0
arr1.forEach( { value in
count += arr2.filter( {$0 == value} ).count
})

Find all similar values in an array and group together into a new array

The problem: I have an array of objects, where the object has an x value. Each object also needs a y value, to be plotted on a Scatterplot. The y value needs to be a number between a min height(.3) and a max height(.6), and be evenly spaced based on the number of equal x values.
For example, if I have an array of objects where [(x=3)(x=4)(x=3)(x=4)(x=5)(x=3)], after iterating through the array I should have a new array of objects that looks like this: [(x=3, y=.3)(x=3, y=.45)(x=4, y=.6)(x=4, y=.3)(x=4, y=.6)(x=5, y=.45)].
The Question: What is the best way to accomplish this performance wise? Are there any packages out there that will help me iterate through the array.
Currently I've created a nested forEach loop, but the code for this is long and feels dirty to me. Any suggestions would be great :)
This is in an angular 4 project (typescript).
You definitely need the map function:
Check documantation at https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Array/map
With map you can transform you array into a new array, this way:
var array = [{"x" : 3}, {"x" : 4}, {"x": 5}, {"x" : 3}];
var counter = 1;
var newArray = array.map(object => {
var calculatedY = counter;
counter++;
//just an example, you have to calculate your y based on your conditions
return { x : object.x, y : calculatedY }
})
console.log(newArray);

Resources