Having trouble with JavaScript concat function not behaving as it should? Can you provide more details to

I am trying to extract all the cities from an object that contains country names as keys and arrays of cities as values. However, my approach seems to be failing and I can't figure out why.

var cities = {
    "United Kingdom": ['london'],
    "Spain": ['ibiza', 'malaga'],
    "USA": ['hollywood']
}

var allCities = [];
for (c in cities) {
    allCities.concat(cities[c]);
}
console.log(allCities); // This returns an empty array

When I try console.log(cities[c]) instead of allCities.concat(cities[c]), I get each city array printed individually:

['london']
['ibiza', 'malaga']
['hollywood']

This issue is quite frustrating for me. Can anyone help identify why this code isn't working as expected?

Answer №1

According to the information provided on the Array.prototype.concat documentation:

The method returns a fresh array that combines this array with additional array(s) and/or value(s).

This implies that it does not alter the original object.

Update to:

mergedCities = mergedCities.concat(citiesList[c]);

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

Store the beginning and ending times in a MySQL database using Sequelize and Node.js

I am currently developing a project management application where I need to keep track of the start and stop time for user work. To achieve this, I have implemented two buttons in the UI - START and STOP. When a user clicks the START button, the following ...

Disregard the popstate triggered by Safari's Initial Page Load

Utilizing pushState, I am able to generate the page view on popstate events based on the history.state of the current page. In cases where there is no history.state present, my intention is to reload the document (hopefully). window.onpopstate = function ...

Issue with Prettier AutoFormatting in a project that combines TypeScript and JavaScript codebases

Recently, I've started incorporating TypeScript into an existing JavaScript project. The project is quite large, so I've decided to transition it to TypeScript gradually. Below is a snippet from my eslintrc.js file: module.exports = { parser: ...

A unique column in the Foundry system that utilizes function-backed technology to calculate the monthly usage of engines over a

In my dataset of ‘Engine Hours’, I have the following information: Engine# Date Recorded Hours ABC123 Jan 21, 2024 9,171 ABC123 Dec 13, 2023 9,009 ABC123 Oct 6, 2023 8,936 XYZ456 Jan 8, 2024 5,543 XYZ456 Nov 1, 2023 4,998 XYZ456 Oct 1 ...

I've recently delved into the world of JavaScript and am currently working on creating a calculator website. However, I'm facing some challenges in getting it to function

I created a calculator code using HTML, CSS, and JavaScript for a website. However, due to my limited experience with JavaScript coding, I encountered some issues. Currently, I have only implemented the number input part (not operations or deletion), but w ...

How to prevent jQuery from continually recalculating width on window resize?

Here is the code I've been working on: http://jsfiddle.net/7cXZj/ var callback = function () { $('.progress-bar').width($('.progress-bar').parent().width() - 190); $(".mainpart-background").animate({ width: "80%" }, 80 ...

I'm having trouble displaying the result of my calculation in the code. Could it be because I forgot to include an output tag?

I am attempting to develop a Miles Per Gallon (MPG) calculator using Javascript. However, I'm encountering difficulties with displaying the results once the "Calculate" button is pressed. <html> <head> <title> MPG Calculator </ti ...

Ensuring User Input Integrity with JavaScript Prompt Validation

I need help with validating input from a Javascript prompt() in an external js file using HTML code. I know how to call the Javascript function and write the validation logic, but I'm unsure how to handle the prompt and user input in HTML. Do I need ...

Exploring the depths of Rx.ReplaySubject: Techniques for delaying the `next()` event

Confused Mind: Either I'm mistaken, or the whiskey is starting to take effect. (I can't rule out the possibility that I'm just going crazy. Apologies for that.) Assumption: My assumption was that ReplaySubject would emit a single value eve ...

Guide on exporting type definitions and utilizing them with npm link for a local package

I am in the process of developing a new testing tool called tepper as an alternative to supertest. My goal is to make this package available in both ESM and CJS formats. However, I'm encountering an issue where users of the library are unable to locat ...

Exploring Angular's Implementation of D3 Force Simulation

Looking to incorporate a d3 force simulation in my Angular app. I have a run method that initializes and sets simulation options, as well as a ticked method that updates the simulation on each tick. However, I've encountered a few problems with this s ...

Flot seems to be having difficulty uploading JSON files

I am relatively new to working with json and flot, but have been tasked with creating a chart. Can someone please help me troubleshoot why my code is not functioning as expected? $.getJSON('chart.json', function(graphData){ alert(graphData); ...

Quick tip on closing an Angular-ui modal from a separate controller

I am currently using Angular-ui to display a modal with a form inside. Here is the code snippet: app.controller('NewCaseModalCtrl', ['$http', '$scope','$modal', function ($http, $scope, $modal, $log) { $scope.ite ...

Error: React JS is unable to access the property 'name' because it is undefined

I recently started working with React. The issue arises when I pass the array object into the map function, triggering an error. Below is the constructor where I've initialized the array object: constructor() { super(); this.state = { d ...

Calculate sums in ReactJS without the need for a button

Adding a few numbers might seem like an easy task, but I've been unable to do so without using an explicit button. // Using useState to handle state changes const [ totalCount, setTotalCount ] = useState(0) // Function to add numbers of differ ...

Personalized dropdown appearance

During my work on a select box, I discovered that custom styling is not possible. I attempted to use some plugins but did not find one that met my needs. I am seeking a dropdown menu with options in both black and gray, similar to this template but using ...

Implementing an onclick function to initiate a MySQL update query

<?php include_once("db.php"); $result=mysql_query("SELECT * FROM stu WHERE receiver='DM4'"); while($row=mysql_fetch_array($result)){ echo "<tr>"; echo "<td>" . $row['ptype'] . "</td>"; echo "<td>" . $row[&apo ...

Calculate the total value of a specific field within an array of objects

When pulling data from a csv file and assigning it to an object array named SmartPostShipments [], calculating the total number of elements in the array using the .length property is straightforward. However, I also need to calculate the sum of each field ...

Learn how to update image and text styles using Ajax in Ruby on Rails with the like button feature

I'm working on implementing a Like button in Rails using Ajax, similar to this example: Like button Ajax in Ruby on Rails The example above works perfectly, but I'm interested in incorporating images and iconic text (such as fontawesome) instead ...

Is it possible to capture and store server responses on the client side using Node.js and React Native?

Here's a POST request I have: router.post("/projects", async (req, res) => { const { projectName, projectDescription, projectBudget, projectDuration, industry, companyName, numberOfEmployees, diamond, } = req.bod ...