Locate a collection of fruits from an array within an array of objects, determine the quantity of each fruit, and add this information to a new array as individual objects

How can I efficiently loop through the array of objects containing fruits and vegetables, compare them with predefined lists of fruits and vegetables, and then filter and sum up the quantities based on these arrays?

I am attempting to create a new array of objects named totalproduce, which should contain the total sum of quantities for fruits, vegetables, and any other items. My approach involves looping through the fruitsnveggies variable using a for loop, and applying if/else conditions to match the items with the predefined lists of fruits and vegetables. However, I am uncertain if my current method is the most effective way to achieve this goal.

var fruits = ["apples", "oranges", "mango"]

var veggies = ["carrots", "onions", "brocoli"]

var fruitsnveggies = [
    { "item": "apples", "quantity": 3},
    { "item": "oranges", "quantity": 2},
    { "item": "carrots", "quantity": 5},
    { "item": "mango", "quantity": 2},
    { "item": "brocoli", "quantity": 3},
    { "item": "chillipowder", "quantity": 3},
    { "item": "onions", "quantity": 3},
    { "item": "ketchup", "quantity": 1},
]

for(var i = 0; i < fruitsnveggies.length; i++){
   if(fruitsnveggies[i]["item"] === fruits[i]){
      //Code here
   }else if(fruitsnveggies[i]["item"] === fruits[i]){
      //Code here
   }else{
     //Code here
   }
}

The expected output should be as follows:


var totalproduce = [
  {"items": "fruits", "quantity": 7},
  {"items": "veggies", "quantity": 11},
  {"items": "others", "quantity": 4}
]

Answer №1

To simplify the process of populating the totalproduce variable, you can utilize a for loop paired with a simple ES6 filter.

var fruits = ["apples", "oranges", "mango"];

var veggies = ["carrots", "onions", "brocoli"];

var fruitsnveggies = [
    { "item": "apples", "quantity": 3},
    { "item": "oranges", "quantity": 2},
    { "item": "carrots", "quantity": 5},
    { "item": "mango", "quantity": 2},
    { "item": "brocoli", "quantity": 3},
    { "item": "chillipowder", "quantity": 3},
    { "item": "onions", "quantity": 3},
    { "item": "ketchup", "quantity": 1},
];

var totalproduce = [
    {"items": "fruits", "quantity": 0},
    {"items": "veggies", "quantity": 0},
    {"items": "others", "quantity": 0}
]

for(var i=0; i < fruitsnveggies.length; i++) {
    var element = fruitsnveggies[i];
    var isAFruit = fruits.find(fruit => fruit == element.item[0]);
    if (isAFruit) {
        totalproduce.items[0].quantity++;
    }
    else {
        var isAVeggie = veggies.find(veggie => veggie == element.item[0]);
        if (isAVeggie) {
            totalproduce.items[1].quantity++;
        }
        else {
            totalproduce.items[2].quantity++;
        }
    }
}

Answer №2

There are multiple issues with your code that need to be addressed:

  • By checking for equality of the 'item' property with a string at a specific index in the 'fruits' array, your code may break when the index goes out of bounds. Additionally, it only verifies if the 'item' matches one of the items in 'fruits' instead of any of them.
  • You mistakenly reference 'fruits' again in your second condition, when you likely intended to reference 'veggies'.

Here is an improved and functional solution:

const fruits = ["apples", "oranges", "mango"]

const veggies = ["carrots", "onions", "broccoli"]

const fruitsnveggies = [
    { "item": "apples", "quantity": 3},
    { "item": "oranges", "quantity": 2},
    { "item": "carrots", "quantity": 5},
    { "item": "mango", "quantity": 2},
    { "item": "broccoli", "quantity": 3},
    { "item": "chilli powder", "quantity": 3},
    { "item": "onions", "quantity": 3},
    { "item": "ketchup", "quantity": 1},
]

const totalProduce = {
  "fruits": 0,
  "veggies": 0,
  "other" : 0
}

fruitsnveggies.forEach(
  (produce) => {
    if (fruits.includes(produce["item"])) {
      totalProduce["fruits"] += produce["quantity"];
    } else if (veggies.includes(produce["item"])) {
      totalProduce["veggies"] += produce["quantity"];
    } else {
      totalProduce["other"] += produce["quantity"];
    }
  }
);

console.log(totalProduce);

Answer №3

One way to achieve this functionality is by utilizing the ES6 functions Array.reduce and Array.includes.

var fruits = ["apples", "oranges", "mango"]
    
var veggies = ["carrots", "onions", "brocoli"]

var fruitsnveggies = [
  { "item": "apples", "quantity": 3},
  { "item": "oranges", "quantity": 2},
  { "item": "carrots", "quantity": 5},
  { "item": "mango", "quantity": 2},
  { "item": "brocoli", "quantity": 3},
  { "item": "chillipowder", "quantity": 3},
  { "item": "onions", "quantity": 3},
  { "item": "ketchup", "quantity": 1},
]

var totalProduce = fruitsnveggies.reduce((map, next) => {
  if (fruits.includes(next.item))
      map.fruits += next.quantity;
  else if (veggies.includes(next.item))
      map.veggies += next.quantity;
  else map.other += next.quantity;
  return map
}, { fruits: 0, veggies: 0, other: 0 })

console.log(totalProduce)

Answer №4

Check out this code snippet on jsfiddle to optimize your use of arrays with filter and reduce instead of lengthy forEach loops and for loops. You can achieve powerful functionality by utilizing these methods. Explore the various methods available for Array here.

const fruits = ["apples", "oranges", "mango"]

const veggies = ["carrots", "onions", "brocoli"]

const fruitsnveggies = [
    { "item": "apples", "quantity": 3},
    { "item": "oranges", "quantity": 2},
    { "item": "carrots", "quantity": 5},
    { "item": "mango", "quantity": 2},
    { "item": "brocoli", "quantity": 3},
    { "item": "chillipowder", "quantity": 3},
    { "item": "onions", "quantity": 3},
    { "item": "ketchup", "quantity": 1}
];

const onlyVegies = fruitsnveggies
  .filter(a => veggies.includes(a.item))
  .reduce((acc, val) => {
    return {
      item: "veggies",
      quantity: acc.quantity + val.quantity,
    }
  }, {item: "veggies", quantity: 0});

const onlyFruits = fruitsnveggies
  .filter(a => fruits.includes(a.item))
  .reduce((acc, val) => {
    return {
        item: "fruits",
      quantity: acc.quantity + val.quantity,
    }
  }, {item: "fruits", quantity: 0});

  const others = fruitsnveggies
    .filter(a => !fruits.includes(a.item) && !veggies.includes(a.item))
    .reduce((acc, val) => {
      return {
        item: "others",
        quantity: acc.quantity + val.quantity,
      }
    }, {item: "others", quantity: 0});

  console.log("result: ", [onlyVegies, onlyFruits, others])

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

Guide to center align fields in Ionic and Angular

I am working on creating a login screen that resembles the image provided. I have managed to set the background image, input fields, and buttons successfully. However, I am encountering a few issues: The width of my input field is taking up the entire spa ...

How is the same-domain policy applied to popup windows that have JavaScript enabled in the URL?

Is it possible to achieve something similar to this? var w = window.open("javascript: makeAnAjaxRequest();"); I'm curious whether the Ajax request, which is triggered after the new window is opened, would be considered a cross-site request. Does the ...

How to extract words from a dynamic router.pathname in NextJS when only the filename is displayed instead of the full path?

I'm keeping this example as straightforward as possible, but I can add more details if needed to solve the issue Currently, I am working with dynamic routes in nextJS. My application fetches data from Twitter based on the keywords entered into the dy ...

Best practices for structuring npm scripts and multiple webpack configurations

My project consists of multiple dashboards, and I've decided to create separate scripts in my package.json for each one. Building all the dashboards during development when you only need to work on one can be time-consuming. So, I discovered that it&a ...

What techniques can I use to modify an object while it's being iterated through?

I've been attempting to manipulate the object while looping through it, but unfortunately, it's not working. How can I modify it so that the constant patient includes the property lastActivity inside the this.model array? My code looks like this ...

When navigating back to the Homepage from another page, React displays the Homepage

Recently, I started learning React and following the Traversy crash course along with an additional video on React router 6+. My route setup looks like this: import { BrowserRouter as Router, Route, Routes } from 'react-router-dom' return ( &l ...

Combine, remove, and maintain the sequence of elements in two arrays using PHP

I am facing a challenge with two arrays structured like this: 1) array(3) { [0]=> string(3) "max" [1]=> string(3) "min" [2]=> string(3) "med" } 2) array(4) { [0]=> string(3) "max" [1]=> string(3) "min" [2]=> string(4) "other" [3]=> ...

What is the best way to rotate a mesh group around the axis of a randomly selected 3D element within the Three.js environment?

I'm currently delving into the intricacies of three.js in order to experiment with a basic mechanism. My end goal is to visualize board tilt (front view) in relation to axle orientation (plan view) for different designs on an XY plot, although that&ap ...

Modify the class's height by utilizing props

Using Vue 3 and Bootstrap 5, I have a props named number which should receive integers from 1 to 10. My goal is to incorporate the number in my CSS scrollbar class, but so far it's not working as expected. There are no error messages, it just doesn&a ...

Accessing keywords from URLs and searching for corresponding details in a database, then retrieving the information in JSON format using PHP

I've got a URL similar to this: www.example.com/?s=test The goal is to search for the keyword 'test' in the MySQL database and retrieve the results in JSON format using PHP. Can anyone provide guidance on how to accomplish this? ...

Tips for boosting the efficiency of replaceWith on Internet Explorer 11

When rendering an array of data in a table element, there is a need for the table to be updated with new data as it can be filtered dynamically. However, I have encountered a performance issue specifically on IE11 when trying to render 1700 data entries us ...

Categorize elements in an array based on a specific keyword

Struggling with my AngularJS (1) application, I can't seem to figure out how to split an array of items into separate arrays grouped by item. In simpler terms, I have an array with different items and I want to group them by their uuid like this: [ ...

Dropzone.js only allows one audio file and one image thumbnail file to be uploaded simultaneously

Is there a way to limit the types of files that can be uploaded through Dropzone.js? Specifically, I want to restrict users to uploading only one image and one audio file. ...

insert the data from an object into every item in an array

My json object is structured like this: { "data": { "id" : 1234, "details": [ { "vid": "332", "long": -79, "lat" ...

Which application server is recommended for both JSON and SOAP API implementations?

As I explore options for selecting an app server platform to handle JSON & Soap POST requests from client applications on Desktops, I am focusing on a Linux-based app server that utilizes PHP code. After conducting research, I discovered a PHP framework b ...

Error encountered: Setting the XMLHttpRequest responseType to "json" results in a SYNTAX_ERR: DOM Exception 12

I've been encountering an issue while trying to set the XHR responseType to "json". Everything seems to be working fine when I keep it as an empty string xml.responseType = "";. However, once I switch it to "json", I'm hit with the console error ...

Utilizing Ionic for local data retention

Seeking assistance with connecting my app to local storage in order to save data on the user's device without resetting every time the app is closed. Struggling to link local storage to an array of objects. Any guidance would be highly appreciated. Re ...

Deleting an element from a JavaScript array

I have a collection of javascript functions that manage intervals by setting and clearing them. The intervals are stored in an array called intervals[]. config: { settings: { timezone: 'Australia/Perth,', base_url: location.p ...

Encountering a null value while parsing JSON within a loop on an Android device

Having trouble extracting the "publisher" key from a JSON object, I keep getting an error. However, when I only extract the "title" key, everything works perfectly fine. public ArrayList<BookData> parseJSON(String jsonString){ try{ ...

Iterate through the xml.documentElement in a loop

I want to show 8 men and 2 women in SVG format. However, my current function only displays one man and woman. How can I add a loop to make this work for all individuals? for (i = 0; i < Serie[n].Number; i++) { return xml.documentElement } The data arr ...