Sorting an array of strings in JavaScript with the help of another array of strings

I am looking for a way to rearrange array1 based on array2.

var array1 = ["cat","dog","mouse","elephant","ant","cow","goat","hen"];
var array2 = ["mouse","cow","goat"];

Expected output:
var another_array = ["mouse","cow","goat", "bird"--- then rest of the values in array1]

Answer №1

Recently extracted from an object in the sequence of values or Infinity for the difference.

var array1 = ["cat", "dog", "mouse", "elephant", "ant", "cow", "goat", "hen"],
    array2 = ["mouse", "cow", "goat"],
    order = array2.reduce((r, k, i) => (r[k] = i + 1, r), {});

array1.sort((a, b) => (order[a] || Infinity) - (order[b] || Infinity));

console.log(array1);

Answer №2

If you need to combine and refine data, consider using concatenation and filtering:

>>> newArray = array2.concat(array1.filter(item => !array2.includes(item)))
    ["mouse", "cow", "goat", "cat", "dog", "elephant", "ant", "hen"]

Answer №3

Here's an example that involves combining elements and applying a filter

const list1 = ["apple", "banana", "orange", "pear", "grape", "kiwi"];
const list2 = ["orange", "kiwi"];
const mergedList = [...list2, "melon", ...list1.filter(fruit => !list2.includes(fruit))]
console.log(mergedList)

Answer №4

Implement the concatenation method

let fruits = ["apple", "orange"];
let vegetables = ["carrot", "spinach", "broccoli"];
let groceries = fruits.concat(vegetables); 
console.log(groceries)

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

Ways to establish a minimum height for material cards using Material UI

I am facing an issue with a card that contains a nested table. The card expands and shrinks based on the size of the table inside it. I want to prevent the card from shrinking when the table has no data or just one entry. Instead, I need the card to mainta ...

Utilizing jQuery to eliminate a script function from an external webpage

Currently, I am utilizing a ColdFusion script to load an external page within the container tag. This external page contains a sorting function defined as: function sorting(sortid). However, this function's sorting criteria constantly leads to errors ...

Taking a Breather with mywindow.print()

I'm currently utilizing a fantastic printing script that I found: <script type="text/javascript"> function PrintElem(elem) { Popup($(elem).text()); } function Popup(data) { var mywindow = window.ope ...

What is the best way to assign attributes to multiple HTML elements using an array?

Seeking assistance to hide various sections in my HTML file upon button click, with the exception of one specific section. Encountered an error message: Uncaught TypeError: arr[i].setAttribute is not a function Here's a snippet of my code: const hide ...

Exploring object data within Laravel blade templates is an essential skill in web development

Below is an example of how the data appears: [ { "id": 22528, "user_id": 25273, "non_sql": "{\"data\": {\"data_1\": \"4\", \"data ...

How can I identify when a node/express ajax request is received?

I have set up a node/express server that sends the ajax-start.html file. Within this file, there is a script that enables ajax requests to be made to the server. Everything functions correctly in this setup. However, I am looking to enhance this process by ...

A guide on displaying a text file from a URL in a reactjs application

When utilizing the code provided below, I have successfully managed to display the content of a local text file on a webpage. However, when attempting to render a text file from a URL, the state becomes null resulting in an empty display. In order to ren ...

Need assistance with debugging the current solution for the todo App using Commander or considering a different approach with Readline and Event Emitter?

I'm currently working on developing a CLI for a Node.js exclusive todo application using the commander and conf modules within Node.js, along with chalk to add color to the output. I've encountered some issues that I'm unsure how to resolve: ...

Combining two variables in AngularJS seamlessly, without explicit instruction

In the realm of Controllers resides my beloved home.js: angular.module("HomeApp", ["BaseApp"]) .controller("MainCtrl", ["$http", "$window", "BaseService", function($http, $window, BaseService) { var self = this; self.posts = BaseServ ...

The drop-down button unexpectedly disappears when using Bootstrap in combination with jQuery autocomplete

I have some javascript code that is structured like: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>jQuery UI Autocompl ...

Storing a Promise in a Variable in React

As a newcomer to JavaScript/React, I am finding it challenging to grasp the concept of using Promise and async. To illustrate, consider the API call getSimById in a JS file that returns a Promise: export function getSimById(simId) { return fetch(simsUrl ...

What is the best way to include a JArray within a JObject without introducing a new key or name for the JArray?

In my .NET C# project, I am attempting to create a new JObject from a JArray. The goal is to retrieve test data for data-driven testing from a FetchData JObject. Here is the code snippet I have developed so far: public static JObject FetchData(string testM ...

Modify the form's action attribute when submitted

I am trying to create a form with multiple buttons that will change the action and target properties when a specific button is clicked. Below is my code snippet: <div id="root"> <form :action="form.action" ref="form" :target="form.target"&g ...

transfer scope variable to scope function

I notice this pattern frequently view: <input ng-model="vm.model"> <button ng-click="vm.method(vm.model)"></button> controller: function Controller() { var vm = this; this.method = function(parameter) { // perform acti ...

Determining if a component is nested within itself in Angular 6 is a crucial task

My goal is to develop a custom Angular component for a nested navigation menu with multiple levels. Below is an example of how the menu structure looks: app.component.html <nav-menu> <nav-menu-item>Section 1</nav-menu-item> <nav- ...

Transform json nested data into an array using JavaScript

Can anyone assist me in converting Json data to a Javascript array that can be accessed using array[0][0]? [ { "Login": "test1", "Nom": "test1", "Prenom": "test1p", "password": "124564", "Email": "<a href="/c ...

Triggering multiple functions by clicking on the Icon

I'm trying to execute two different functions when the user clicks on the Icon, but I keep getting an error that says: Expected onClick listener to be a function, instead got a value of object type. Can someone please help me figure out what I am doin ...

JavaScript: Creating a new entry in a key-value paired array

I am in the process of creating a dynamic menu for use with jQuery contextMenu. I have encountered an issue when trying to add a new element, as it keeps showing the error message 'undefined is not a function'. The menu functions correctly witho ...

"Encountering a problem with numerous callbacks in the getJSON method

I am working on creating marker pop ups that display information from different ajax requests on a map. In order to make the second call, I utilize an userID obtained from the first call. While the information from the second call is displayed correctly, ...

The issue of race condition in Node.js programming

I've been diving into the documentation, but I'm struggling to figure out what's going on here. I have two functions: one downloads a CSV file via a URL, and the next function takes that CSV file and converts it to JSON FileDownload.js co ...