What is the best way to efficiently loop through elements and add them to a new array in JavaScript while optimizing performance?

Here's the code in question:

let newArr = []

const items = [
    {
        name: 'JTB 0110-01',
        offers: ['one', 'two']
    },
    {
        name: 'LOBA CHEMIE',
        offers: ['three', 'four', 'five']
    },
    //more
]

items.forEach(item => {
    item.offers.forEach(i => newArr.push(i));
})

//more code

My goal is to iterate over the items array and push each offers property to a new array.

While the code works, I want the iteration to be completed before moving on to the next section of code. How can I achieve this?

Update

Apologies for the confusion. I am looking for a way to make the iteration synchronous, so that the loop finishes before proceeding to the next part of the code.

Answer â„–1

If you're looking for a way to combine arrays in JavaScript, you can leverage the power of Array#concat along with the spread syntax ... and a mapped array.

var items = [{ name: 'JTB 0110-01', offers: ['one', 'two'] }, { name: 'LOBA CHEMIE', offers: ['three', 'four', 'five'] }],
    array = Array.prototype.concat(...items.map(({offers}) => offers));

console.log(array);

Answer â„–2

To make your code more efficient, you can utilize the spread syntax along with the reduce method.

Using the reduce() method, you can apply a function to an accumulator and each element in the array, ultimately condensing them into a single value.

const items = [ { name: 'JTB 0110-01', offers: ['one', 'two'] }, { name: 'LOBA CHEMIE', offers: ['three', 'four', 'five'] }]
let result = items.reduce(function(acc,elem){
  acc.push(...elem.offers);
  return acc;
},[]);
console.log(result);

Answer â„–3

To merge the values of the offer key, one can utilize the spread syntax.

let newArr = []

const items = [{
    name: 'JTB 0110-01',
    offers: ['one', 'two']
  },
  {
    name: 'LOBA CHEMIE',
    offers: ['three', 'four', 'five']
  }

]
var newArray = [];
items.forEach(function(item) {
  // // ... is spread syntax which will combine the array
   newArray.push(...item.offers)
})
console.log(newArray)

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

Utilize Jquery to dynamically update form input in real time based on checkbox selections

I am working on a form that requires real-time calculation of GST (Goods and Services Tax) directly within the form (GST = Price/11) This functionality has been implemented with the following script. Additionally, the calculation needs to be adjust ...

Selecting a "non-operational" collection location on an e-commerce platform

Recently I discovered a bug on an online shopping website. It seems that by using inspect element, it was possible to alter the HTML code and change an unavailable pickup point to available. This allowed me to place an order, make a payment, and even recei ...

Change the value in Vue through a single action (swapping out buttons)

I created a custom component that allows users to add points only once by clicking a button. I want to add an undo option to decrease the point value by 1 after it has been added. When a point is added, I'd like the button to change color to red and d ...

What is the process for inserting a watermark onto an image as it is being retrieved from Firebase?

I am developing a React website where I need to implement a feature that adds a watermark to an image when it is retrieved from Firebase storage. Is there a way to apply a watermark while accessing the image from the storage? I have already looked into Ho ...

execute the function within the data() method

I'm currently working on retrieving data for my search tree, and I'm facing issues with fetching the data directly from axios or calling a function because it cannot be found. export default { name: 'SideNavMenu', data () { return ...

Receive the button click event outside of the canvas

Is there a way to have separate click events for the button and the ListItem? My focus is on the button click event only, without triggering the ListItem event. Live DEMO import React from "react"; import ReactDOM from "react-dom"; import ListItem from ...

How to properly size a child div inside a parent container

I'm having trouble with sizing a child div inside a parent div. The problem is that the child div's size changes according to the number of elements it contains, but I want all the child divs to be the same size regardless. This issue arises with ...

Obtain the latest NPM package versions

I am currently seeking a way to compile a comprehensive list of all major versions that have been released for a specific NPM package. By utilizing the following API link, I can retrieve a list of available versions which includes both the major and exper ...

Adjust the database table when a session expires in PHP

Within my PHP code, there is a session timeout feature that triggers after 60 minutes of inactivity. This code snippet resides in the file /mno.php, where both the login and logout functionalities are also implemented. /mno.php if (isset($_SESSION[' ...

The route is redirecting to an incorrect destination

Whenever a button is clicked on my webpage, this particular function is triggered. $scope.go=function(takenAt){ var path = '/oneMinuteMetric/loadCapturedMetrics?'+'&timestamp=' + takenAt + '&tagName='+ $stateParam ...

Next.js appending [object%20Object] to the URL's endpoint

I encountered an error when launching my next app using "npm run dev". The error occurred during the pre-render attempt: GET http://localhost:3000/aave/fundamentals/economics/[object Object] [HTTP/1.1 404 Not Found 434ms] The issue is not specific to thi ...

Customizing a thumbnail script to dynamically resize and display images according to their size properties

I am attempting to modify a simple JavaScript script that enlarges an image from a thumbnail whenever it is clicked. The issue I am facing is that the enlarged image is displayed based on a fixed width size. I want the enlarged image to be displayed accord ...

Guide on utilizing the h function in Vue3 for seamless binding and passing of properties and events from parent to child components

Utilizing Vue3 and naive ui for front-end development has been a challenge for me as I primarily focus on back-end development and lack expertise in front-end technologies. To enhance user interaction, I incorporated naive ui’s BasicTable along with an ...

Get an Array Using AJAX in PHP and JavaScript

Section 1 I want to retrieve an Array from PHP and use it in JavaScript. I have created a file using the fwrite function in PHP, then included that file in my next .load method inside a Div. The new PHP file contains an "include 'somefile.php';" ...

In JavaScript, you can use the document.cookie property to delete specific cookie values identified by their names and values

Within my JavaScript code, I am working with a cookie that contains multiple names and values: "Token=23432112233299; sessionuid=abce32343234" When I download a file from the server, a new cookie is added to the document, resulting in the following cooki ...

Linux web server blocking requests across different domains, even with correct Access-Control-Allow-Origin headers set

I am facing an issue with my Ubuntu web server running a React app. There are two files on the server that handle requests made by the website, but for some reason, clients are unable to make requests to the server. Server.js: const express = require(&apos ...

The RSS feed reader is currently malfunctioning

I'm having trouble loading an RSS feed from the following URL: http://solutions.astrology.com/scripts/it.dll?cust_id=aamfha&doc=daily07short/dailyshort.xml Here is the code I am using to try to read it: url = 'http://solutions.astrology.co ...

Transform and command the data acquired through an AJAX request using jQuery

My code includes an AJAX call using jQuery: $('.add a').click(function() { $.ajax({ type: 'POST', url: '/api/fos', context: this, datatype: 'html', success: function(data) ...

Using jQuery to implement interactive hover effects on individual items within a list

I'm currently developing a project that involves displaying speech bubbles next to each list item when hovered over. These speech bubbles contain relevant information specific to the item being hovered on. To achieve this functionality, I've crea ...

Is there a way to pause and await the completion of an axios post request within a different axios interceptor?

Here are my axios interceptors: instance.interceptors.request.use( (config) => { const accessToken = localStorage.getItem("access_token"); const auth = jwt_decode(accessToken); const expireTime = auth.exp * 1000; co ...