Guide to executing insertion sort for two arrays in ES6

Imagine having arrays:

arr1 -

[90, 44, 64, 16, 24, 20, 64, 86, 20, 64, 56, 72, 16]

along with

arr2 -

[21, 13, 9, 13, 15, 7, 17, 15, 9, 19, 7, 15, 9]

The goal is to implement insertion sort for these two arrays and obtain the sorted result array:

[
  90, 86, 72, 64, 64, 64, 56, 44,
  24, 21, 20, 20, 19, 17, 16, 16,
  15, 15, 15, 13, 13,  9,  9,  9,
   7,  7
]

I am aware that concatenating and sorting can work but might not be optimal in terms of performance.

If you have suggestions on how to achieve the above using ES6 features, please share!

Answer №1

Combine arrays using spread operator and then use arrow function for sorting:

let arr1 = [90, 44, 64, 16, 24, 20, 64, 86, 20, 64, 56, 72, 16];
let arr2 = [21, 13, 9, 13, 15, 7, 17, 15, 9, 19, 7, 15, 9];

let resultArray = [...arr1, ...arr2].sort((a, b) => b - a);

console.log("arr1:");
console.log("["+arr1.join(", ")+"]");
console.log("arr2:");
console.log("["+arr2.join(", ")+"]");
console.log("resultArray:");
console.log("["+resultArray.join(", ")+"]");
.as-console-wrapper { max-height: 100% !important; top: 0; }

Experimenting with larger Arrays:

let arr1 = [90, 44, 64, 16, 24, 20, 64, 86, 20, 64, 56, 72, 16];
let arr2 = [21, 13, 9, 13, 15, 7, 17, 15, 9, 19, 7, 15, 9];

for(let i=0; i<10; i++) {
  arr1 = arr1.concat(arr1);
  arr2 = arr2.concat(arr2);
};

let start = null;
let resultArray = null;

start=new Date();
resultArray = [...arr1, ...arr2].sort((a, b) => b - a);
console.log("First resultArray took " + (Date.now() - start) + "ms");

start = null;
resultArray = null;
start=new Date();
resultArray = arr1.concat(arr2).sort(function(a, b) {return b - a});
console.log("Second resultArray took " + (Date.now() - start) + "ms");
.as-console-wrapper { max-height: 100% !important; top: 0; }

Observations show that

let resultArray = [...arr1, ...arr2].sort((a, b) => b - a);
seems to take longer compared to
resultArray = arr1.concat(arr2).sort(function(a, b) {return b - a});
...

Answer №2

To combine two sorted arrays, you can sort them individually and then merge them:

const sortedArray1 = array1.sort((a, b) => b - a);
const sortedArray2 = array2.sort((a, b) => b - a);
const mergedArray = [];
let index1 = 0;
let index2 = 0;
while (index1 < sortedArray1.length && index2 < sortedArray2.length) {
    if (sortedArray1[index1] >= sortedArray2[index2]) {
        mergedArray.push(sortedArray1[index1]);
        index1++;
    } else {
        mergedArray.push(sortedArray2[index2]);
        index2++;
    }
}
while (index1 < sortedArray1.length) {
    mergedArray.push(sortedArray1[index1++]);
}
while (index2 < sortedArray2.length) {
    mergedArray.push(sortedArray2[index2++]);
}
// The mergedArray now contains the fully sorted elements from both arrays

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

Encountering an error that states "this.push is not a function" when trying to select the 2nd or 3rd option

My goal is to extract elements from a drop-down menu and populate a list box based on the selection. The selected value from one list box should then be transferred to another list box, specifically from Available to Selected. However, while selecting Deve ...

Transferring files to Django using AJAX

I am struggling with the process of uploading files to django using ajax. The upload is done within a modal window. The Form <div class="modal fade bs-example-modal-lg" id="fileUploadModal" role="dialog" aria-hidden="true"> <div class="modal ...

Creating a Composite of Several Boxes in THREE.js

My goal is to display multiple boxes together in a specific structure shown in the image I have attached. I am interested in testing the GPU limitations by increasing the number of boxes, and then later on, I will focus on optimization. The framework I am ...

Exploring new classes with jQuery's .not() and :not()?

I am working on a memory game where I need to flip cards and check if two are equal. My issue is that I do not want the function to run when clicking on a card that is already flipped, or on another flipped card. I tried using jQuery's .not() and :no ...

When using Next.js revalidate, an error may occur stating: "There are keys that require relocation: revalidate

I have been attempting to utilize the revalidate function in my code by following the example provided by Vercel. However, I keep encountering an error. Here is the snippet of code that I am currently using: export async function getServerSideProps() { c ...

"Enhance User Experience with jQuery Autocomplete using String Arrays

Within my web form model (AdtFormModel), there is a variable: public List<String> TemoinsVille { get; set; } I opted for a list structure as I intend to allow users to dynamically add more 'TemoinsVille' inputs in the form. Currently, ...

To successfully handle this file type in Next.js, make sure you have the necessary loader configured as no loaders are currently set up to process this specific file

I encountered an issue when trying to load an image from a local directory in my Next.js application Failed to compile ./pages/components/image.png 1:0 Module parse failed: Unexpected character '' (1:0) You may need an appropriate loader to hand ...

GLSL: Utilizing varying amounts of textures in the sampler2D

Is there a way to dynamically pass an array of textures to shaders through a uniform sampler2D in Three.js? In the code snippet below, I am attempting to send two textures to the shaders and initialize the uniform value texture with a length of 2. However ...

Is it necessary to incorporate Babel into a project that involves developing a backend service using Node.js and a front-end component using the EJS view engine?

I find myself a little confused. Some say that if you are working on pure Node.js projects, there is no need to stress about this issue. However, for web development, it's important to be familiar with these tools. On the other hand, some recommend us ...

Missing CSS class after a jQuery replaceWith? Need help resolving this issue?

I made a recent addition to the master.cs page. <h4 class="hideAndShow">[ - ] Hide</h4> Here's the corresponding code in my CSS file: .hideAndShow { position: fixed; top:120px; right:420px; color: white; background-c ...

Utilize AngularJS to efficiently filter an array based on selections made in a combobox

I have experience filtering an array using an input text as the filter. However, I am curious if it is possible to utilize the filter property of AngularJS with a combobox as the filter options. For instance, imagine I have an array of years: [2014,2014,2 ...

Is there a way to change the data type of all parameters in a function to a specific type?

I recently created a clamp function to restrict values within a specified range. (I'm sure most of you are familiar with what a clamp function does) Here is the function I came up with (using TS) function clamp(value: number, min: number, max: number ...

Include a message for when there are no results found in the table filter

I am currently working with a code that filters a table, but when there are no results, the table appears blank. Can someone assist me in adding a "No results found" message to display when nothing is found? $(document).ready(function() { $("#table_s ...

What is the best way to separate a string into individual words?

Seeking guidance on splitting strings into words without relying on strtok or any function other than main. Can someone provide assistance with the implementation? void main() { int i; int myargc = 1; char *myargv[256]; char buff[100]; ...

Is it possible to retrieve the controller path for an AJAX request from within a partial view?

Looking for a solution to fully decouple and reuse a partial view that allows users to select dates and filter results based on those dates. This widget can be used on multiple pages, so I wanted to add event listeners that would submit the form within the ...

Visualization of extensive datasets in JavaScript

I'm currently developing a dashboard in JS for displaying sales data plots to users. Can anyone recommend a JavaScript library that meets the following criteria: Capable of plotting a large number of points (ex: 100k or more) Interactive functional ...

Adding a background behind the currency symbol before the textbox field

I need to customize a text field like the one shown in the image below: https://i.sstatic.net/gu3JA.png After making some quick adjustments, I ended up with the following result. My main concern is now the background of the currency symbol. https://i.ss ...

Ensure that your JQuery code only runs after Angular has completed its rendering

As a newcomer to Angular JS, I may have a question that seems silly. Despite seeing it discussed in several SO questions, I still couldn't figure it out. My goal seems simple, yet I've had a tough time achieving it. I'm attempting to execut ...

Challenges with Data Transfer in VueJS and VUEX

Here is the code snippet for my component: <div id="event-picker"> <template v-for="event in $store.state.events"> <a href="#" v-on:click.prevent="$store.dispatch('prepareEventForm', event)& ...

Is it possible to remove one array from another array?

I have two arrays: list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] list2 = [2, 4, 6, 8, 10] Is there a way to transform these arrays to produce the following output? list3 = [1, 3, 5, 7, 9] list3[i] = list1[i] - list2[i]; Unfortunately, I encountered an issue ...