Combining two arrays with varying lengths based on their values

Seeking assistance with a programming task that is straightforward yet challenging for me.

There are two arrays: one long and one short.

var arrayShort = [
  {
    id: 'A',
    name: 'first'
  },{
    id: 'B',
    name: 'second'
  },{
    id: 'C',
    name: 'third'
  }
]

var arrayLong = [
  {
    id: 'A',
    name: 'firstSub1'
  },{
    id: 'A',
    name: 'firstSub2'
  },{
    id: 'A',
    name: 'firstSub3'
  },{
    id: 'B',
    name: 'secondSub1'
  },{
    id: 'B',
    name: 'secondSub2'
  },{
    id: 'B',
    name: 'secondSub3'
  },{
    id: 'C',
    name: 'thirdSub1'
  },{
    id: 'C',
    name: 'thirdSub2'
  },{
    id: 'C',
    name: 'thirdSub3'
  }
]

Looking to merge them based on shared ids, resulting in:

var arrayCombined = [
  {
    id: 'A',
    name: 'first'
  },{
    id: 'A',
    name: 'firstSub1'
  },{
    id: 'A',
    name: 'firstSub2'
  },{
    id: 'A',
    name: 'firstSub3'
  },{
    id: 'B',
    name: 'second'
  },{
    id: 'B',
    name: 'secondSub1'
  },{
    id: 'B',
    name: 'secondSub2'
  },{
    id: 'B',
    name: 'secondSub3'
  },{
    id: 'C',
    name: 'third'
  },{
    id: 'C',
    name: 'thirdSub1'
  },{
    id: 'C',
    name: 'thirdSub2'
  },{
    id: 'C',
    name: 'thirdSub3'
  },
]

Essential

Sequential order matters.

My Attempts

for (var i = 0; i < arrayShort.length; i++) {
  var itemShort = arrayShort[i]
  console.log(itemShort)
  for (var j = 0; j < arrayLong.length; j++) {
        var itemLong = arrayLong[j]
    if (itemLong.id === itemShort.id) {
      console.log(itemLong)
      arrayShort.splice(j + 1, 0, arrayLong)
    }
  }
}


var arrayCombined = arrayShort
console.log(arrayCombined)

This code leads to an infinite loop without clear reasons. I am aware of the risks associated with nested loops and conditions.

Thinking about better approaches mentally or with code?

Codepen link, access dev tools for details

Remarks:

  • Preference for Vanilla JavaScript solutions, although options with Lodash or Underscore are welcome. These libraries could simplify the process, but understanding their usage challenges me.
  • Struggling with appropriate search terms for this task...any suggestions?

Appreciate any feedback/recommendations.

Answer №1

Utilize the concat and sort functions to organize your arrays

var arrayCombined = (arrayShort.concat(arrayLong).sort(function(a,b) {


            return (a.id > b.id) ?  1 : 
                  ((a.id < b.id) ? -1 : 0);

})).sort(function(a,b) {

            return (a.name > b.name) ?  1 : 
                 ((a.name < b.name) ? -1 : 0);

});;

console.log(arrayCombined);

Check out the resulting output below

[ { id: 'A', name: 'first' },
  { id: 'A', name: 'firstSub1' },
  { id: 'A', name: 'firstSub2' },
  { id: 'A', name: 'firstSub3' },
  { id: 'B', name: 'second' },
  { id: 'B', name: 'secondSub1' },
  { id: 'B', name: 'secondSub2' },
  { id: 'B', name: 'secondSub3' },
  { id: 'C', name: 'third' },
  { id: 'C', name: 'thirdSub1' },
  { id: 'C', name: 'thirdSub2' },
  { id: 'C', name: 'thirdSub3' } ]

Answer №2

When using the lodash library, you have the ability to achieve the following:

var arrayOne = [
    { id: 'X', name: 'apple' },
    { id: 'Y', name: 'banana' },
    { id: 'Z', name: 'cherry' }
];

var arrayTwo = [
    { id: 'X', name: 'appleSub1' },
    { id: 'X', name: 'appleSub2' },
    { id: 'X', name: 'appleSub3' },
    { id: 'Y', name: 'bananaSub1' },
    { id: 'Y', name: 'bananaSub2' },
    { id: 'Y', name: 'bananaSub3' },
    { id: 'Z', name: 'cherrySub1' },
    { id: 'Z', name: 'cherrySub2' },
    { id: 'Z', name: 'cherrySub3' }
];

_(arrayOne)
    .union(arrayTwo)
    .sortByAll('id', 'name')
    .value()

// Output:
// [
//   { id: 'X', name: 'apple' },
//   { id: 'X', name: 'appleSub1' },
//   { id: 'X', name: 'appleSub2' },
//   { id: 'X', name: 'appleSub3' },
//   { id: 'Y', name: 'banana' },
//   { id: 'Y', name: 'bananaSub1' },
//   { id: 'Y', name: 'bananaSub2' },
//   { id: 'Y', name: 'bananaSub3' },
//   { id: 'Z', name: 'cherry' },
//   { id: 'Z', name: 'cherrySub1' },
//   { id: 'Z', name: 'cherrySub2' },
//   { id: 'Z', name: 'cherrySub3' }
// ]

With the union() method, you can combine arrays without affecting either original array and the sortByAll() function allows for sorting by multiple properties.

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

What is the significance of static in react?

export class NavMenu extends Component { static displayName = NavMenu.name; constructor (props) { super(props); this.toggleNavbar = this.toggleNavbar.bind(this); this.state = { collapsed: true }; } I attempted to research the ...

Determine if an Android application has been installed using JavaScript or jQuery

I'm working on an Android app that is also accessible via a web browser. I want to add a banner prompting users to install the Android application if they haven't already. How can I use JavaScript or jQuery to detect if the user has the app insta ...

Is it possible to alter the JSON file being loaded in AngularJS by passing a variable?

I am in need of loading the content from either food1.json or food2.json, and I am attempting to achieve this within the html template: <body ng-controller="MainCtrl" ng-init="init('food1')"> Subsequently, in the JavaScript code: $scop ...

When attempting to process JSON using the fetch method, the value for a valid JSON key

Currently, I am facing a challenge wherein I need to fetch data from my REST server to populate the frontend of my UI. This requires me to make requests not only to my own server but also to other servers. One specific request involves retrieving a list of ...

The loop seems to be disregarding the use of jQuery's .when() function

I've encountered a challenge with a custom loop that needs to perform a specific function before moving on to the next iteration. Below is the code snippet: function customIteration(arr, i) { if (i==arr.length) return; var message = arr[i]; ...

What is the best way to retrieve the transpiled string from babel-core?

I've been attempting to utilize babel with npm and it seems like the necessary package is babel-core. My goal is to provide it with a string of ES6 code and receive a transpiled code string in return. It sounds simple enough, but I'm having troub ...

Difficulty with linking a CSS property to an HTML element using JavaScript

I'm currently working on building a custom carousel from scratch. Instead of using pre-made code snippets, I decided to challenge myself by creating one using setTimeout in JavaScript. However, I seem to be encountering an issue that I can't quit ...

What could be causing the SyntaxError with JavascriptExecutor: Unexpected identifier?

Python PythonExecutor py = (PythonExecutor) driver; Boolean ready = (Boolean)py.executeScript("the following Python code"); Python Code var ready = False; window.onload = def check_ready(): ready = True def sleep(): return new Promise(resolve = ...

What is the most straightforward method to convert a current Express node app into a static site?

After primarily working with React and create-react-app, I've grown accustomed to the convenience of having a build utility for npm that simplifies deploying projects to static web hosting platforms like github pages or surge. This process ultimately ...

When executing npm run dev, an UnhandledPromiseRejectionWarning is triggered

I'm encountering an UnhandledPromiseRejectionWarning error when running npm run dev on my Vagrant machine, and I'm struggling to identify the root cause. The console output suggests that a promise is not being properly completed with the catch() ...

The useParams() function is returning undefined, even though the parameter does exist in the destination URL

I have a complete inventory of items called "Commandes" (PS: the app is in French), displayed in a table with a column for each row that should redirect me to another component showing more details about the selected row. To achieve this, I need to utilize ...

Vanish and reappear: Javascript block that disappears when clicked and shows up somewhere else

My goal is to make three squares randomly disappear when clicked on the page. However, I am facing an issue where some of them, usually the 2nd or 3rd one, reappear elsewhere on the page after being clicked. I have created a jsfiddle to demonstrate this: ...

The perfect way to override jest mocks that are specified in the "__mocks__" directory

Within the module fetchStuff, I have a mock function named registerAccount that is responsible for fetching data from an API. To test this mock function, I've created a mock file called __mocks__/fetchStuff.ts. Everything seems to be functioning corre ...

implementing select2 and binding an event to it

I have a simple select2 setup where I am passing a common class in the options and trying to trigger a jQuery event on every change or click of an item in the dropdown. Here is my code snippet: <select name="transferfrom" id="transferfrom" data-placeho ...

I'm having trouble getting my accordion menu to work properly. Whenever I click on the question title, the answer doesn't seem to show up or collapse. What could be causing this issue?

I am currently working on a project to create an accordion menu where the answers are hidden and only revealed upon clicking the question. However, when I test it out, nothing happens when I click on the question. Here is my code: .accordion-Section ...

Generating unique spreadsheet identifiers in an HTML file

When it comes to displaying a chart using Google Sheets, I encounter an issue where the data is sourced from the same spreadsheet: function updateChart() { var ui = HtmlService.createHtmlOutputFromFile('ChartLine').setWidth(1350).setHeight(550) ...

Guide on how to bypass IDM when downloading a PDF file through a GET request

When I try to fetch a PDF by sending a GET request to the server and open it in a new tab, IDM interrupts my request and downloads the file instead. It changes the server response status to 204 and removes the headers. How can I prevent IDM from doing th ...

npm ERROR: Unable to install the package named "<packageName>" because it conflicts with an existing package of the same name

Currently, I am attempting to incorporate the jsonfile package into my project. However, I am encountering a couple of errors: An issue arises when attempting to install a package with the same name as another package within the same directory. (Despite ...

Error encountered at / - undefined local variable or method `parameters' for main:Object (Executing Stripe Charge with Stripe.js)

Encountering an error with the code below while attempting to create a Stripe charge using Stripe.js. Below is my web.rb file: require 'json' require 'sinatra' require 'sinatra/reloader' require 'stripe' get &a ...

Updating JSON Data Retrieved from C# AJAX Request

During my ajax call, I am fetching JSON data that is being returned from a query. The current JSON response looks like this: [{ "label": "", "value": "2302" }, { "label": "9 - Contract set-up in EPICOR", "value": "2280" }, { "label": " ...