How to display all objects in an array with identical names using JavaScript?

I'm working with an array that looks like this

var items = [];
items.push({
    name: "milk",
    id: "832480324"
});
  items.push({
    name: "milk",
    id: "6234312"
});
 items.push({
    name: "potato",
    id: "983213"
});
  items.push({
    name: "milk",
    id: "131235213"
});

Now I have created a function called order(name, amount). If I were to use it as follows: order(milk, 2), the function should return 2 ID's for milk in the items array. What would be the best approach to achieve this task? (Creating a new question was necessary!)

Answer №1

Follow this basic for loop example

var groceries = [];
groceries.push({
  item: "bread",
  code: "12345"
});
groceries.push({
  item: "milk",
  code: "67890"
});
groceries.push({
  item: "eggs",
  code: "54321"
});

function findItem(itemName, quantity) {
  var result = [];
  
  for (var j = 0; j < groceries.length && quantity > 0; j++) {
    if (groceries[j].item === itemName) {
      result.push(groceries[j].code);
      quantity--;
    }
  }
  
  return result;
}
console.log(findItem('milk', 1));

Answer №2

I find the ES6 method that I really appreciate for its simplicity and ease of understanding is using filter().map().slice():

var items = [{name:"milk",id:"832480324"},{name:"milk",id:"6234312"},{name:"potato",id:"983213"},{name:"milk",id:"131235213"}];

function order(name, amount) {
  return items.filter(i => i.name === name)
              .map(i => i.id)
              .slice(0, amount);
}

console.log(order('milk', 2));

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

Using the getElementsByTagName method in JavaScript to target elements within another

What is the reason behind the output being 0 in this code? <p id="g"> <div>kk</div> <div>ee</div> <div>jff</div> </p> <script type="text/javascript"> var ii = document.getElementById( ...

Searching for a specific value in an array with jQuery: A step-by-step guide

I am looking to search for a specific value within an array and retrieve its index. Sample HTML: <div class="container"> <div class="col-md-6"> <div id="task0">Task0</div> </div> <div class="col-md-6"> &l ...

Textures have been added by the user in the three.js platform

Click here to access the jsFiddle adaptation of this problem. In my quest to develop a cutting-edge 3D web application, I aim to allow users to choose an image file from their device: <input id="userImage" type="file"/> Once a file is selected, th ...

Transforming text into visual content using a live preview div powered by jQuery

Looking for a way to display images in real-time as a user types letters into a textarea field. When a user inputs a letter like 'k', an image associated with that letter should appear. Currently, only pre-entered letters on the page show images, ...

Using JavaScript to determine the time it will take to download something

Hi everyone, I'm a beginner in javascript and I am currently working on finding the download time of a file. I have calculated the size of the file and divided it by the current time, but unfortunately, I am not getting the correct result. This is th ...

How to increase a bytearray in Python 3?

What is the best way to increment a 16-byte array in Python 3, from 0x00000000000000000000000000000000 to 0x00000000000000000000000000000001? import base64 import Crypto from Crypto.Cipher import AES def incr(): k = b'\x01\x00\x0 ...

The Javascript code I wrote is unable to detect the array element that was initially defined in Python

Trying to launch a new browser window through Selenium using driver.execute_script("window.open('');") However, the goal is to open a specific link provided by the user. For this purpose, extracted the link input from an array and inc ...

Tips for sending <p> data to a router function with HTML

I am currently working on a page where users are presented with a list of unverified accounts, each containing its own form element. Each form has a "submit" button that triggers a POST call to /verify. However, I am facing an issue where the data within t ...

What is the best way to store a downloaded video from the server?

I am currently in the process of downloading a video from a server using JavaScript XHR (specifically Angular $http GET with response type 'blob'). My question is, how can I save this downloaded video to a Chrome application's local storage ...

NodeAutoComplete: Enhanced Autocompletion for Node.js

I am attempting to utilize autocompletion of a JavaScript file with Node.js and Tern. However, the documentation for Ternjs is incredibly lacking. const tern = require("tern"); const ternServer = new tern.Server({}); const requestDetails = { "qu ...

Calling Node Express request inside a GET route

I am currently utilizing nodejs as an intermediary layer between my public website and an internal server within our network. Through the use of express.js, I have created a basic REST api where the endpoint should trigger a request call to a webservice a ...

Error Encountered with Custom Ajax File Uploader's .AjaxSubmit() Function

I am working on a multipart form that allows users to upload images using AJAX. Here is the HTML code: <form name="mainform" id="mainform" class="form_step" action="" method="POST" enctype="multipart/form-data"> <!-- This image acts li ...

What happens when a value is shifted beyond its size boundary and it does not equal to 0?

New and Improved Question: Why is the result not printing as expected when using the shift operation in this code snippet? #include "stdafx.h" #include <iostream> #include <string> int _tmain(int argc, _TCHAR* argv[]) { unsigned char bar ...

Make Fomantic-UI (Angular-JS) sidebar scroll independently

Is there a way to make a sidebar scroll independently of the content it pushes? Currently, my page is structured like this: -------------------------- |[button] Header | -------------------------- |S | Main content | |i | ...

Tips for persisting nested arrays of objects data with Mongoose

Currently, I am transmitting data from an angular reactive form. Here is the UI image of the Angular reactive form: Angular reactive form UI image Additionally, here is the image showing the data being sent to the backend in the browser console: Data bein ...

Discovering dates in a single array by utilizing the intervals from another array and identifying the nearest value

I am working with two Nested NumPy arrays (dateValArr & searchDates). The array dateValArr holds all the dates for May 2011 (1st - 31st) along with their associated values. Similarly, the array searchDates contains 2 dates with their respective values, ...

Enabling Multiple Login Feature in Node.js

const handleLogin = async (req, res) => { const User = require("../models/user"); const LoginInfo = require('../models/login_info'); try { const { email, mobile, password, otp } = req.body; const params = []; if(ema ...

Implementing Pagination Functionality Using Knockout.js

Sample JSON Data [{ "name": "A Goofy Movie (1995) 720p HDTVRip x264 Eng Subs [Dual Audio] [Hindi DD 2.0 - English DD 2.0] Exclusive By -=!Dr.STAR!=-", "progress": 0, "size": "1.06 GB", "downloaded": "87.98 KB", "hash": "8fe65e43464debe ...

"Enhancing user experience with CSS hover effects on dynamically loaded content and mobile devices

I have developed a quiz with 2 answer options for each question. To prevent the questions from loading initially, visitors must click a start button, triggering the questions to load via Ajax. The issue I am facing is that when a question is answered, the ...

Leveraging async/await within a React functional component

Just getting started with React for a new project and facing challenges incorporating async/await functionality into one of my components. I've created an asynchronous function called fetchKey to retrieve an access key from an API served via AWS API ...