简体   繁体   中英

Two arrays, same length. If first array values equals true get values from second array

I have two arrays. They are always the same length. If userEmotions[index] value is true I need to add userTimeData[index] value to a variable:

var userEmotions = [false, true, false, true],
    userTimeData = [140, 320, 730, 50],
    userPercentage = 0;

// e.g add 320 and 50 to userPercentage:
// userPercentage == 370

How do I go about achieving this?

You can use a for loop:

 var userEmotions = [false, true, false], userTimeData = [140, 320, 730], userPercentage = 0; for (i = 0; i < userEmotions.length; i++) { //loop the length of the array if (userEmotions[i]) { // check userEmotions is true userPercentage += userTimeData[i]; // if it is add userTimeData to percentage } } console.log(userPercentage); 

You could use Array#indexOf for the first single value or zero as default value.

 var userEmotions = [false, true, true], userTimeData = [140, 320, 730], userPercentage = userTimeData[userEmotions.indexOf(true)] || 0; console.log(userPercentage); 

For getting an array of values, you could filter the values.

 var userEmotions = [false, true, true], userTimeData = [140, 320, 730], userPercentages = userTimeData.filter((_, i) => userEmotions[i]); console.log(userPercentages); 

The OP wanted alternative approaches, so:

 userEmotions = [false, true, false], userTimeData = [140, 320, 730], userPercentage = userEmotions .map(x => x ? 1 : 0) .map((x, i) => x * userTimeData[i]) .reduce((a,b) => a+b); console.log(userPercentage); 

Why over engineer it, a simple for loop solves your problem -

 var userEmotions = [false, true, false], userTimeData = [140, 320, 730], userPercentage = 0; for (i = 0; i < userEmotions.length; i++) { if (userEmotions[i]) { userPercentage += userTimeData[i]; } } console.log(userPercentage); 

can you try this :

for(let i = 0 ; i < userEmotions .length ; i++){
   if(userEmotions[i]){
       userPercentage = userTimeData[i]
   }
}

Let me know if it help you :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM