1

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?

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.