Manipulating the logical conditions of VueJs using an array of elements

I'm working with an array within my data function where I need to calculate the sum of numbers that have a false record. The challenge I'm facing is setting up the logical parameter for computing only the false arrays. How should I define this condition in the computed section?

Array1: [
                {Text1: "Some text in an array 1", Numbers: Math.floor(Math.random() * 50), B1: true},
                {Text2: "Some text in an array 2", Numbers: Math.floor(Math.random() * 50), B1: true},
                {Text3: "Some text in an array 3", Numbers: Math.floor(Math.random() * 50), B1: true},
                {Text4: "Some text in an array 4", Numbers: Math.floor(Math.random() * 50), B1: true},
                {Text5: "Some text in an array 5", Numbers: Math.floor(Math.random() * 50), B1: true},
                {Text6: "Some text in an array 6", Numbers: Math.floor(Math.random() * 50), B1: false},
                {Text7: "Some text in an array 7", Numbers: Math.floor(Math.random() * 50), B1: false},
                {Text10: "Some text in an array 8", Numbers: Math.floor(Math.random() * 50), B1: false},
                {Text8: "Some text in an array 9", Numbers: Math.floor(Math.random() * 50), B1: false},
                {Text9: "Some text in an array 10", Numbers: Math.floor(Math.random() * 50), B1: false},
            ],
            sum: 0
computed:{
    sumOfNumbers(){
        return this.Array1.reduce((sum, numbers) =>{
            return sum += numbers.Numbers;
        }, 0)
    },
    sumOfFalse(){
        if(Array1[iii].B1 = 'false'){
            return this.Array1.reduce((sum, numbers) =>{
                return sum += numbers.Numbers;
            }, 0)
        }
    },
},

Answer №1

If you want to filter out all elements in an array with a falsy B1 value, you can utilize the Array.prototype.filter method:

const falsyB1Items = this.Array1.filter(item => !item.B1)

Afterwards, you have the option to reduce these filtered items:

return falsyB1Items.reduce((sum, numbers) => sum += numbers.Numbers, 0)

Check out the demo for reference.

Answer №2

Here is a simple way to achieve the desired result using just one function:

computed: {
    calculateSum() {
        this.arrayOfValues.map(item => {
            if (item.condition === true) {
                this.total += item.value;
            }
        });
        return this.total;
    }
}

Would you like to give this method a try?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Interact with a JSON API using JavaScript by incorporating dynamic user input

Recently, I delved into tutorials on utilizing JSON data and JavaScript. Feeling inspired, I decided to create a simple app using an API. However, I encountered a hurdle and I'm struggling to identify its cause. The problem seems to be related to how ...

Having trouble displaying the desired formatting when mapping through nested JSON in Node ES6

Currently working on a project to build a photo gallery using nested JSON data. My goal is to iterate through the data and create a well-structured JavaScript object or a smaller JSON file that includes only the text and image URL nodes. However, my curren ...

Steps to generate a new page when submitting a form:

When a form is submitted, I am aiming to generate a fresh page each time. This new page will serve as an order status tracker that will be updated regularly. Essentially, my goal is for users to see a confirmation page for the form submission and have acce ...

Can you explain how to break down secured routes, users, and posts all within a single .create() function in Mongoose/JavaScript

I am seeking guidance on utilizing the .create() method within a protected route while implementing deconstructed JavaScript. In the absence of the protected route, I can deconstruct my schema and utilize req.body in .create(...) as shown below. const { ti ...

Verify in Jquery whether a table row contains no elements with a specified class before removing any duplicates

I have an HTML table: <div class="1233">hello</div> <table cellpadding="0" cellspasing="0" class="sortable zebra tablesorter tablesorter-default" id="articles-table"> <thead> <tr class="tablesorter-headerRow"> ...

Adjust the color of TextareaAutosize component using mui in React

Just starting out with React and getting acquainted with mui components. Experimenting with setting the color of a TextareaAutosize mui component using this code: import * as React from 'react'; import TextareaAutosize from '@mui/material/T ...

Guide to dynamically using array.map based on a condition in React

I am encountering an issue with a modal screen that contains two dropdowns and a text input field. The problem arises when the second dropdown is set to “is empty”, as the text input field should then disappear, leaving just the two dropdown inputs on ...

Accessing parent libraries from an Iframe: A step-by-step guide

Currently, I'm developing a web application utilizing an embedded web server that restricts me from modifying the HTTP header to enable file caching. One issue I've encountered is that whenever I update the src of an iframe in my app, it forces a ...

Verify the presence of plain ASCII text

I need to verify if the file uploaded is in ascii plain text format. Can you suggest a method? $("#my_file").change(function(){ //alert if file is not ascii plain text }); <input type="file" name="my_file" id="my_file" /> ...

Which is better for creating contour graphs: JavaScript or PHP?

I need to create a scientific graph for a web application that displays temperature data based on time and depth coordinates. You can view an example here : I have time and depth coordinates, and I want to represent temperature using color in the graph, ...

Having trouble showing JSON data with select option in Laravel Vue

I am struggling to display the value in Options with province_id and province as it always appears in JSON format. Can someone please help me with this issue? This is my create.js file: changeShippingCountry(country) { this.$set(this.form.shippin ...

What are the reasons behind the failure of this regex matching in Angular specifically on Safari browser?

In my angular project, I have the following code. It works perfectly fine in Chrome and Firefox, but in Safari, it throws an exception. var shour = "9:00:00 PM CDT"; var ehour = "12:00:00 AM CDT"; var conver_shour = shour.match(/^(\d+):(\d+)/)[ ...

Checking for the existence of keys in a PHP array

I am faced with a challenge involving two arrays. My goal is to return either TRUE or FALSE based on whether the two arrays match each other. Specifically, I need to consider un-ordered arrays as a match if the results match, but true should only be return ...

Display only one difference when the document is loaded, then reveal the other divisions after the "change"

For my business options form, I am working on a feature where the user selects an Entity Type (such as Corporation, LLC, LLP) from a dropdown menu and then a new form appears. Here is what I have attempted: HTML FILE <head> <link rel="styles ...

Ensure the text area box is validated upon clicking a specific radio button

Hello, my HTML code looks something like this: <input type="radio" name='answer_value1[<?php echo $survey1->id?>]' value="<?php echo $answer1->id?>" validate="required:true" id="<?php $answer1->valdt == '1' ? ...

Hold off on refreshing the page until all the $.get calls have finished executing

I am currently using a piece of JavaScript to execute an Ajax call which returns XML data. This XML is then processed, and another Ajax call is made for each "record" found in the XML to delete that record. However, I am facing an issue where the JavaScrip ...

What is the best way to reveal a hidden div using JavaScript after a form submission?

jQuery is not a language I am very familiar with, but I am attempting to display a simple animated gif when a form is submitted. When users click 'submit' to upload an image, I want the gif to show to indicate that the image is being uploaded. Th ...

Having difficulty parsing key value pairs from a JSON object using JavaScript

I'm encountering difficulties with parsing a Json_encode response in a JavaScript function. The PHP script retrieves data from a database and sends the output as a Json_encode array to an HTML page. <?php include("connect.php"); try { ...

The fetch API in Javascript encounters issues when employed within an EJS file

I'm attempting to retrieve a file named files.json from the main directory of my locally hosted NodeJS backend and then display its contents in the console. <script> fetch("./files.json") .then(res => { return res.json() ...

The zip() operator in RxJS is not functioning as intended. It consistently finishes execution without emitting any values

Suppose you have an observable containing a large number of elements, say 450 or more. You want to transfer these elements to a different observable in batches of 100 elements each. You can check out a functional example provided by @martin at this link: ...