What is the process for adding elements to an array, then sorting it in JavaScript and returning the sorted array

Having an issue with my code snippet below, My goal is to insert a new record at the beginning of the array and then sort it based on the label. However, I'm encountering an unexpected outcome where the array turns out empty.

const array = [{id: '3', name: 'name1'},
                {id: '4', name: 'name2'},
               {id: '5', name: 'name3'}]

const items = array
      .map((sp) => ({ label: sp.name, value: sp.id }))
      .splice(0, 0, { label: '', value: '' })
      .sort((a, b) => a.label - b.label);

console.log(items);

Answer №1

Is this the desired outcome?

const myArray = [
    { id: '7', name: 'apple' },
    { id: '8', name: 'banana' },
    { id: '9', name: 'orange' }
]

const elements = myArray.map((el) => ({ title: el.name, number: el.id }))
elements.unshift({ title: '', number: ''})
elements.sort((x, y) => x.number - y.number);

console.log(elements);

Key:

[
  { title: '', number: '' },
  { title: 'apple', number: '7' },
  { title: 'banana', number: '8' },
  { title: 'orange', number: '9' }
]

The unshift function is utilized to insert a new element at the beginning of an array. Both sort and unshift operate in place, meaning they modify the original array rather than returning a new one.

Answer №2

The issue with the code lies in the misunderstanding of how the .splice() method works. Contrary to what might be expected, the .splice() method actually returns an array of removed elements and does not alter the original array itself. To rectify this misconception, it is necessary to assign the output of .splice() back to the original array:

const array = [{id: '3', name: 'name1'},
{id: '4', name: 'name2'},
{id: '5', name: 'name3'}]

const items = array
      .map((sp) => ({ label: sp.name, value: sp.id }))
      .splice(0, 0, { label: '', value: '' })
      .sort((a, b) => a.label - b.label);

array = items;

console.log(array);

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

Arranging strings in descending order using Typescript

I was attempting to arrange a string[] in a descending order. This is what I have come up with so far: let values = ["Saab", "Volvo", "BMW"]; // example values.sort(); values.reverse(); Although this method is effective, I am wondering if there is a mo ...

Express Angular Node Template Render throwing an error: module 'html' not found

I am currently in the process of creating a web application using AngularJS with ui-router for routing via $stateProvider, ensuring that only the specified states are displayed in the ui-view. In my server.js file, I have set up an initial framework such ...

How can we protect against CSRF attacks?

My typical approach involves using AJAX to input data into a MYSQL database like this: $.ajax({ url: "writescript.php", type: "POST", data: { data : mydata,//this could be anything }, success: function (html) { //do something ...

Is it possible to verify the existence of several arrays of data in a MongoDB database using Node.js?

I'm trying to verify if certain data exists in a database. If the data does exist, I want to set the value of k to 1. global.k = 0 let roll = {roll0:"1616",roll1:"234"} for (let i = 0; i < inputcount; i++) { let obj1 = roll["roll" + i]; const ...

The initialized Javascript array solely consists of undefined elements, without any of the expected values

I was under the impression that I knew how to declare JavaScript arrays, but in this particular script, I seem to be stuck in an infinite loop of undefined elements within the array. In my code, I define three arrays containing numbers—two with multiple ...

Troubleshooting Issue with React Router Component Displaying Blank Page

I have been working with React Router in an attempt to connect my App.js and Car.js components. I have included {this.props.children} in both components, but the connection is not functioning as expected. When I deploy my app, there is no sign of the Car.j ...

Possible rephrased version: "Encountering a Jquery clash

It appears that the issue causing my problem may be a Jquery conflict. Please correct me if I am wrong after reviewing the information below. I am new to Jquery and attempting to add a dropdown plugin to a website. The attempt is successful, but an existi ...

Preventing the default behavior using event.preventDefault() does not seem to be effective when submitting a

Why is the event.preventDefault() method not functioning properly? <script type="text/javascript" src="vue.js"></script> <div id="app"> <form v-on:submit.prevent="saveData"> <input type="text" name="test"> <button ...

Generate dynamic thumbnails for every object using React

Hey there! I'm currently working on creating a div for each thumbnail in my personas ={[]}. I want to use this.props.personas.map to achieve this. Here's what I have so far: {this.props.personas.map(thumbnail => { return <div>< ...

Sending Information within Controllers with AngularJS

I have a unique scenario in my application where I need to pass input from one view to another. I have set up a service as shown below: .service('greeting', function Greeting() { var greeting = this; greeting.message = 'Default&ap ...

Unusual actions observed with that particular button

Currently, I am working on creating a pomodoro clock using Codepen. While I acknowledge that my code isn't flawless yet, I have encountered a peculiar behavior with the Start button. When I click on it once, the timer starts as expected. However, if I ...

JavaScript - Modify input character prior to appending it to the text area

I am working on creating a virtual keyboard using jQuery. Whenever I press 'a' in the textarea, I want it to display 'z' instead. In my investigation of typing a letter in the textarea, I discovered the following sequence: keyDown ev ...

Examining a React component through unit testing using Jest and Enzyme

I am currently conducting unit tests on a React component. One component is importing another and utilizing its props. Below are the JSX files: class First extends React.PureComponent { render() { const { name, isSelected, onClick } = this.pro ...

"PHP Dilemma: Navigating the Ajax Button Press Situation

I've been attempting to create a button that triggers a PHP script on a webpage and updates only a specific div tag, but so far I haven't had any success. Removing the $ajax section of the script allows my buttons to change states, but as soon as ...

Issues encountered with the functionality of face-api and tensorflow.js within the browser

I've been trying to execute this example in the browser Check out the example here Specifically looking at this code snippet <!DOCTYPE html> <html> ... (Contents of the code snippet) ... </body> </html> Unfortunately, I&apos ...

Changing the structure of a JSON array in JavaScript

I'm currently developing an ExpressJS application and I need to send a post request to a URL. My data is being retrieved from a MS SQL database table using Sequelize, and the format looks like this: [ { "x":"data1", "y":& ...

Tips for eliminating all line breaks in a Node JS application's console log statement

I am currently working on a NodeJS application using Express. While logging is functioning correctly for most files and libraries, I have noticed that many of them, even those beyond my control, contain line breaks in the logs. My objective is to ensure ...

The Vue store array declaration triggers a TS error stating that it is not assignable to a parameter of type never

I'm puzzled as to why this error keeps showing up: Argument of type '{ id: string; }' is not assignable to parameter of type 'never'. ... appearing at const index = state.sections.findIndex((section) => section.id === id); T ...

Implementing Q promise library in Express.js with Mongoose

Recently, I delved into the world of promises while working on an Express.js/MongoDB application that I developed. One of my routes queries MongoDB and then assigns the result as a property on an object in the render method arguments (which is used by th ...

Break down a string into an array containing a specific number of characters each

I'm currently working on a project that involves tweeting excerpts from a book daily via a small app. The book's content is stored in a text file and I need to split it into 140-character-long strings for posting. Initially, I tried using the s ...