Building an array by combining elements from two separate arrays

I have a collection of objects, each object containing different names.

[ "John", "Alice", "Bob", "Eve" ]

There is also another array of objects:

[ { name:"Alice", value: 345 }, { name: "John", value: 678 }, { name: "Eve", value: 987 } ]

To create a new array, I want each element to be a sub-array with the name and value pairs. The order of elements should match the first array of names.

For example:

[ ["John", 678], ["Alice", 345], ["Bob", undefined], ["Eve", 987] ]

However, when I tried to implement this, my output was incorrect as the values were not in the correct order.

var order = ["John", "Alice", "Bob", "Eve"];
var values = [{ name: "Alice", value: 345 }, { name: "John", value: 678 }, { name: "Eve", value: 987 }];

var newArray = order.map(function(name, i) {
  return [name, (values[i] && values[i].value)];
})

console.log(newArray)

Answer â„–1

If you want to retrieve items in a specific order, consider using a Map.

var names = [ "Foo", "Bar", "Test", "Other" ],
    objects = [{ name: "Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 }],
    map = new Map(objects.map(({ name, value }) => [name, value])),
    result = names.map(name => [name, map.get(name)])

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer â„–2

You're getting closer to the solution - all that's left is to discover the right value:

var order = ["Foo", "Bar", "Test", "Other"];
var values = [{ name: "Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 }];

var array = order.map(function(name, i) {
  return [name, values.some(e => e.name == name) ? values.find(e => e.name == name).value : undefined];
})

console.log(array)

Utilizing ES5 syntax:

var order = ["Foo", "Bar", "Test", "Other"];
var values = [{ name: "Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 }];

var array = order.map(function(name, i) {
  return [name, values.some(function(e) { 
    return e.name == name;
  }) ? values.find(function(e) {
    return e.name == name;
  }).value : undefined];
});

console.log(array)

Answer â„–3

Take a look at my solution below. I hope you find it helpful.

const arrayA = [ "Apple", "Orange", "Banana", "Grapes" ];
const arrayB = [ { name:"Orange", value: 200 }, { name: "Apple", value: 150 }, { name: "Grapes", value: 500 } ];

const result = arrayA.map((item) => [ item, (arrayB.find(({ name }) => name === item) || {}).value ])

console.log(result)

Answer â„–4

To retrieve the corresponding "name" in the "values" array, you must utilize the entries specified in the "order" array.

var order = ["Foo", "Bar", "Test", "Other"];
var values = [{ name: "Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 }];

var newArray = order.map(function(key, i) {
  let foundItem = values.find(({name}) => name === key);
  return [key, foundItem && foundItem.value ];
})

console.log(newArray)

Answer â„–5

To extract values from a found item, you can utilize the map function along with Object.values. Alternatively, you may provide a default value if the item is not found.

const arr1 = [ "Foo", "Bar", "Test", "Other" ];

const arr2 = [ { name:"Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 } ];

const res = arr1.map(e => Object.values(arr2.find(({name}) => name === e) || ({name: e, value: undefined})));
console.log(res);

Answer â„–6

const items = ["Apple", "Banana", "Pear", "Orange"];
const prices = [{ category: "Banana", cost: 2.5 }, { category: "Apple", cost: 3.0 }, { category: "Orange", cost: 1.5 }];
const summary = [];
items.forEach((item) => {
let found = false;

prices.forEach(price => {
    if (item === price.category) {
summary.push([item, price.cost]);
        found = true;
}
});
if (!found) {
    summary.push([item, undefined]);
}
});

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

Manipulating Arrays

Wondering how to reposition and structure the answers in an array accurately or formulate a SQL query for the desired outcome? I've been struggling with this for the past few days. <?php public function fetchQuestions() { $sql = &a ...

Performing an additional GET request using AngularJS

After successfully running the code snippet, I received the JSON output displayed below. My main focus now is on extracting the cars_url. What would be the most effective method to retrieve the URL (and what approach is recommended), and subsequently initi ...

Extracting the name of a track from the /r/listenToThis subreddit for an IFTTT automation script

I have a list of songs gathered from this subreddit, presented in the following format: [ "Lophelia -- MYTCH [Acoustic Prog-Rock/Jazz] (2019)", "Julia Jacklin - Pressure to Party [Rock] (2019)", "The Homeless Gospel Choir - I'm Going Home [Folk ...

The browser automatically adds a backslash escape character to a JavaScript object

When attempting to send an MQTT message to a topic from my angular app, the message needs to be in a specific syntax: { "Message": "hello" //the space after : is mandatory } However, upon sending the message in the correct format, the browser aut ...

AJAX and JSON-powered PHP form validation

My PHP script encodes validation in JSON, but I'm unsure how to integrate it into my main JavaScript function. Regular expressions are used in the PHP script to validate form criteria and I need to pass this information to the JavaScript file to displ ...

Navigating shadow dom elements in HTML with Selenium WebDriver

public WebElement retrieveShadowRootElement(WebElement element) { WebElement shadowRoot = (WebElement) ((JavascriptExecutor)driver) .executeScript("return arguments[0].shadowRoot", element); return shadowRoot; } WebElement rootElement= dri ...

Is there a way I can turn off the dragging functionality in my situation?

Is there a method to disable the dragging functionality within a draggable element? $('#dragitem').draggable({ scroll : false, drag: function(event, ui){ //check if condition is met if(†...

Building a loading bar using dots

<span class="dot"></span> <span class="dot"></span> <span class="dot"></span> <span class="dot"></span> <span class="dot"></span> <span class="dot"></span> <span class="dot">< ...

mongodb cannot locate the schema method within the nested container

Trying to access a method of a schema stored inside a mixed container has presented a challenge. The scenario is as follows: var CaseSchema = mongoose.Schema({ caseContent : {}, object : {type:String, default : "null"}, collision : {type : Boo ...

Merging several arrays into a single multidimensional associative array with PHP

I am in need of combining three arrays into a multidimensional associative array. Original Data $statiosnIds = [12, 17, 20, 32]; $distances = [0, 2.5, 3.0, 6.2]; $orders = [0, 1, 2, 3]; Desired Output $data = [ [ 'station_id' ...

I am encountering an issue in Nextjs with mongoose where it seems that the function mongoose.model() is not

In my E-commerce app built with Next.js and utilizing Mongoose, I defined a productSchema (models/Product) like this: const mongoose = require("mongoose"); const productSchema = new mongoose.Schema( { title: { type: String, required: true } ...

How can the sum of elements in an Array be shown as an output? [Java]

I've been trying to create a basic program that calculates and displays the total sales for all 12 months of the year based on user input. Despite looking at similar examples and tutorials, I'm still struggling to fully understand the process. Ca ...

Create and store custom variables in tinyMCE.init for future reference

After making this tweak: article_id: <?php echo $edit ?> }); I have added the code at the end of the tinyMCE.init function. My goal is to retrieve the article id within the simpleimage plugin and use it for an AJAX query to fetch a list of ...

Execute a JavaScript transition upon clicking following the display block

Can someone assist me with creating a simple transition from right to left when I click on a button? To better explain, I have set up an example here: https://jsfiddle.net/Waarx/9kjhnwLp/22/ var button1 = document.querySelector('#div1'); butt ...

Restrict HTML Elements Based on Their Size

I have a text file with a substantial amount of content that I need to display in an HTML format. The challenge is that I only want to show a portion of the text on the screen, but I am unsure of the exact amount that needs to be displayed. What I do know ...

Challenges arise when trying to maintain a div aligned to the far right of the browser window as the dimensions of the browser change, especially after applying an

I have a main container div that holds two smaller divs side by side. When one of these smaller divs is clicked, it moves to the far left or right side of the browser window depending on which one was clicked. This functionality works perfectly as intended ...

My current assignment involves creating a recursive function that will output the numbers from an array that correspond to prime index values

I am faced with the challenge of creating a recursive function that will display all the numbers in an array with prime indexes. Although I have a good comprehension of recursion, I struggle when it comes to void functions. This is the code I have writte ...

How to align a div in the center of a cell with Bootstrap

I am currently working with Bootstrap 3 and I have a specific requirement to center a div within a cell in the container row. Most resources I found only mention how to center a div within the entire container, which is not what I am looking for. My goal i ...

Explore the data visualization capabilities of Angular Elements

Utilizing Angular elements to embed an angular page within an existing Spring-Boot project has been a seamless process thus far. An inquire button triggers the loading of data from the backend in the component typescript file, which is subsequently displa ...

Utilize Web3.js to interact with a specific function in a deployed smart contract on the Ethereum blockchain from a React application

I am attempting to execute the transferMargin() function from the Synthetix Contract on Optimism Kovan using react/javascript (web3.js) and Metamask. I am encountering an issue where I am unable to successfully trigger the transferMargin function upon a Bu ...