Snk
Snk

Reputation: 149

Math with typescript array - Angular

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?

Upvotes: 1

Views: 375

Answers (2)

Passionate Coder
Passionate Coder

Reputation: 7294

You can also try this

  1. loop in to your array
  2. 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)

Upvotes: 1

Barremian
Barremian

Reputation: 31115

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);

Upvotes: 3

Related Questions