Top method for combining an array prefix with a reversed array prefix

When given two arrays and indices, the task is to combine a portion of the first array with a reversed portion of the second array.

For instance:

// Provided Input
arr1 = [1,2,3,4,5,6,7,8,9];
arr2 = [10,11,12,13,14,15];
ind1 = 6;
ind2 = 3;

// Expected Output
arr = [1,2,3,4,5,6,12,11,10];

This is my current implementation:

function Concat(arr1,arr2,ind1,ind2) {
    let arr = [];
    for (let n = 0; n < ind1; n++)
        arr.push(arr1[n]);
    for (let n = ind2; n > 0; n--)
        arr.push(arr2[n-1]);
    return arr;
}

I am open to suggestions on how this can be improved in terms of efficiency or simplicity. Any ideas?

Answer №1

Consider trying out the following approach:

Note: While this may not offer a significant speed improvement over your current method, it does provide a cleaner solution.

function CombineArrays(arr1,arr2,index1,index2) {
  return [].concat(arr1.slice(0, index1), arr2.slice(0, index2).reverse());
}

arr1 = [1,2,3,4,5,6,7,8,9];
arr2 = [10,11,12,13,14,15];
index1 = 6;
index2 = 3;

console.log(CombineArrays(arr1, arr2, index1, index2))


As mentioned earlier, the performance impact of this method is not substantial. You can compare the results here on js-perf.


An alternative approach is available if you have the flexibility to modify the input structure.

By expecting an array of objects in a specific order, we can simplify the code and make it more generic. Assuming the structure as follows:

Kindly consider the syntax, as my primary language is TypeScript which influences my writing style.

interface CombinedStructure {
  values: Array<any>;
  endIndex: number;
  shouldReverse: boolean
}

This structural change enhances readability and makes the code easier to customize.

function CombineCustomData(arr) {
  return arr.reduce(function(acc, cur) {
    var tempArray = cur.values.slice(0, cur.endIndex);
    if (cur.shouldReverse) {
      tempArray = tempArray.reverse();
    }
    return acc.concat(tempArray);
  }, []);
}

var inputData = [{
    values: [1, 2, 3, 4, 5, 6, 7, 8, 9],
    endIndex: 6
  },
  {
    values: [10, 11, 12, 13, 14, 15],
    endIndex: 3,
    shouldReverse: true
  }
]

console.log(CombineCustomData(inputData))

Answer №2

To solve this without any issues, you can utilize the following code:

var arr1 = [1,2,3,4,5,6,7,8,9];
var arr2 = [10,11,12,13,14,15];
var ind1 = 6;
var ind2 = 3;
var output = [...arr1.slice(0, ind1), ...arr2.slice(0, ind2).reverse()];
console.log(output);

If you prefer not to employ ES6 spread syntax, you can opt for array.prototype.concat:

var arr1 = [1,2,3,4,5,6,7,8,9];
var arr2 = [10,11,12,13,14,15];
var ind1 = 6;
var ind2 = 3;
var output = arr1.slice(0, ind1).concat(arr2.slice(0, ind2).reverse());
console.log(output);

Answer №3

Easiest way to merge two arrays

Example:

// array declaration
let firstArray = [1,2,3,4,5,6,7,8,9];
let secondArray = [10,11,12,13,14,15];
let indexOne = 6;
let indexTwo = 3;
var mergedArray = [];

// adjust length based on indexes
firstArray.length = indexOne;
secondArray.length = indexTwo;

// reverse and concatenate the arrays
mergedArray = firstArray.concat(secondArray.reverse());
console.log(mergedArray);

Efficient and clear approach.

Answer №4

Utilizing ES6 features

let arrayOne = [1,2,3,4,5,6,7,8,9],
    arrayTwo = [10,11,12,13,14,15];
let indexOne = 6,
    indexTwo = 3;

let newArray = [...arrayOne.slice(0, indexOne), ...arrayTwo.slice(0, indexTwo).reverse()];

console.log(newArray)

Answer №5

If you need to combine multiple arrays, consider utilizing this technique. It enables you to merge any number of arrays in a specific order using the function cascading concept. You can chain together this cascading approach and take advantage of optional parameters for reversing the order if needed.

const arr1 = [1,2,3,4,5,6,7,8,9];
const arr2 = [10,11,12,13,14,15];

const obj = {
  items: [],
  concat(arr, index, isReverse = false) {
     let temp = arr.slice(0, index);
     this.items = this.items.concat(isReverse ? temp.reverse() : temp);
     return this;
  }
};

obj.concat(arr1, 6).concat(arr2, 3, true);
console.log(obj.items);

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

Switching views in AngularJS by using a controller to control the content displayed in the

My JavaScript web app utilizes AngularJS to simplify tasks, but I've encountered an issue. I'm trying to change views from an ng-controller using $location.path, but for some reason, the view isn't updating even though the path in the $loca ...

How is it possible for me to access any route beyond localhost and still reach my homepage?

Currently, I am working on a ReactJs project that utilizes a REST API to fetch information about Pokemon including stats, names, and images. Despite setting up my Routes using React Router, I am encountering an issue where all routes redirect me to the sam ...

"Utilizing JQuery's addClass, removeClass, and appendTo functions to

Having a bit of an issue trying to implement a functionality where options inside a div can be clicked and moved to another div, and if they are clicked again in the other div, they will return back. Here is the code snippet: $(".selectable").bind(&ap ...

Unable to retrieve cookies from the client side | Working with NodeJS and JavaScript

Code for Handling Cookies on the Server-Side: res.cookie('test', 'value', { expire: 400000 + Date.now(), httpOnly: false }); res.writeHead(302, { 'Location': 'localhost:4000/test', }); res.end(); Code for Acce ...

Checking with jQuery Validate: displaying an error message if input matches a certain value

I spent 6 hours trying to figure out a solution to my issue. Currently, I am utilizing the jQuery Validation plugin. In my form, there is a password input field. When an AJAX request detects an incorrect password, another input field is set to a value of ...

Displaying an alert on a webpage that shows a label input using JavaScript and

I'm currently working with HTML5 and JavaScript and I'm facing a challenge. I want to create a feature where users can input any word into a label, and when they click on a button, an alert is triggered with the given text. However, despite my ...

What is the best way to export my mongo schema to a file and then utilize it for inserting data?

I've been encountering difficulty when attempting to insert data into my collection. I'm not entirely sure if I'm doing it correctly, so I apologize for the vague request. Hopefully, by providing you with my code, you can help me understand ...

Inconsistencies observed in the behavior of Rails JavaScript assets with respect to

Currently delving into the world of Rails while also incorporating Angular into my project. Let's build a basic application from scratch. 1). Start off by creating a new Rails app: rails new hello_rails 2). Include the angular gem in your Gemfile ...

Dialog component from HeadlessUI doesn't support the Transition feature

Currently working with Next.JS version 14.1.3 I recently integrated the <Dialog> component from HeadlessUI and configured TailwindCSS. However, I encountered an issue where the Modal window doesn't have any transition effects even though I foll ...

JSON object containing multiple elements in JavaScript

I have a JavaScript JSON object const student = { name: "bob", age: 7, grade: 6 } and I can send it to my Web API using the axios POST command with JSON.stringify(student) To build multiple student objects from an array by looping through and p ...

Utilizing Delphi to Pass a Dynamic Array of Records to a Function

Having a Dynamic array of Records, I am looking to pass one of the items in the array to a function by reference. For example, let's say AArray[1].arecorditem is a string of 6 characters String[6] The function would be - function dosomething(var A ...

Mastering the use of setInterval and setTimeout with callback functions in Node.js is crucial for

Building an application in Node.js to serve as the engine for a simulator game like a football match. My goal is to implement an "on-line broadcast" feature, so I have created functions for this purpose. However, I am facing issues with my code and cannot ...

JS for accessing Meteor templates through the DOM

This is a meteor template I created: {{#each p}} <div class="cpl"> <div class="chat-post"> <li class="post"> <div class="nm" id={{_id}}> <a>{{username}}</a> </div> < ...

Encountering an issue where React is unable to identify the `handleChange` prop on a DOM element

I am attempting to create a login form in React, but I keep encountering this issue. React is throwing an error stating that the handleChange prop is not recognized on a DOM element. If you want it to be shown as a custom attribute in the DOM, please use ...

Utilizing accordion headers with linked images in AngularUI

I came across a helpful post on Stack Overflow that explains how to incorporate header images in an AngularUI accordion. I'm curious if there's a way to use the image as a hyperlink to a website, excluding the text in the header. Appreciate any i ...

Using Ramda to transform an array of key-value pairs into an object

Utilizing Ramda to organize a normalized model object by key involves converting it to key|value pairs (similar to Object.entries) and sorting by the first value using R.head (which represents the key when in pairs) The goal is to transform the resulting ...

Inserting a large number of records in MySQL using a batch insertion method

Currently, I am facing an issue with inserting multiple records into a MySQL table at once. Just so you know, I am using Node.js along with MySQL (you can find more information about it here: https://www.npmjs.com/package/mysql) Here is what I have been ...

Guidelines for setting up a universal Handler using React and AXIOS

In my current project, I am utilizing ReactJs and AXIOS. My goal is to implement a global error handler without having to add a catch statement to each request throughout the codebase. To achieve this, I have created a service that consolidates all request ...

Retrieving the video length from a URL using JavaScript

To determine the length of videos from a URL provided by an API, I am looking for a solution using JavaScript. For instance, if the URL is I aim to extract and display the duration alongside the video title without altering any HTML elements. The goal is ...

Display conceal class following successful ajax response

Upon clicking the button, the following script is executed: $.ajax({ url: "<?php echo CHILD_URL; ?>/takeaway-orders.php", type: 'POST', async:false, data: 'uniq='+encodeURIComponent(uniq)+'&menu_id=' ...