In Javascript, if the name value is not filled in, I will need to set it to the last item in the array

I am working with an array in JavaScript. When the name value is empty, I want to move it to the end of the array. How can I achieve this?

Example:

 const data : [
   {
     id:0,
     name:"gorkem"
   }
   {
     id:1,
     name:""
   }
   {
     id:2,
     name:"ahmet"
   }
 ];

After Replacement:

const data : [
   {
     id:0,
     name:"gorkem"
   }
   {
     id:2,
     name:"ahmet"
   }
   {
     id:1,
     name:""
   }
 ];

Answer №1

To separate the items based on whether their names are empty or not, utilize two filter calls - one to extract non-empty names and the other for empty names. Finally, merge these two arrays together.

const nonEmptyNames = data.filter(item => item.name);
const emptyNames = data.filter(item => !item.name);
const mergedArray = nonEmptyNames.concat(emptyNames);

Answer №2

To achieve a reversed sort order based on the truthiness of the "name" property, you can simply sort the array accordingly.

const data = [{
    id: 0,
    name: "John"
}, {
    id: 1,
    name: ""
}, {
    id: 2,
    name: "Alice"
}];

console.log(data.sort((a,b) => !a.name - !b.name));

In this code snippet, we are leveraging the fact that an empty string is evaluated as falsy (equivalent to 0), while a non-empty string is considered truthy (equivalent to 1). By negating these values with '!', we can achieve the desired reverse sorting order and treat them as booleans.

Result:

[
    {
        "id": 0,
        "name": "John"
    },
    {
        "id": 2,
        "name": "Alice"
    },
    {
        "id": 1,
        "name": ""
    }
]

Answer №3

To begin, ensure you have a valid array:

const information = [{
    id:0,
    name:"John"
}, {
    id:1,
    name:""
}, {
    id:2,
    name:"Anna"
}];

With that in place, you can utilize a loop to eliminate any empty name entries and move them to the end of the array:

for (let index = 0; index < information.length; index++) {
    if (information[index].name === '') {
        let value = information[index];
        information.splice(index, 1);
        information.push(value);
    }
}

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 proper technique for implementing async pipe in place of utilizing subscribe in Angular?

Instead of using subscribe, I am considering utilizing the async pipe "| async". This alternative will replace my current subscription code shown below: ngOnInit(): void { this.activatedRoute.url .pipe(takeUntil(this.unsubscribe$)) .subscribe(s ...

After attempting to publish my NPM package, I encountered an issue where I received an empty object. This occurred despite utilizing a setup that includes ES6, Babel,

Is there anyone out there who can assist me with this issue? I am attempting to publish an npm package with the following configuration: webpack: production: { entry: [ './src', './src/app.scss', 'draft- ...

Several JavaScript functions require a confirmation dialog to be displayed before they can be executed

There are three separate javascript/jquery functions in my code, all triggered by a button click. One function posts to a form handler, another creates a new tab, and the third one sends new data into the tab through an ajax call. These functions are inter ...

Automatically populate the options of a dropdown menu using jQuery

I am a beginner in the world of Javascript, JSON, and jQuery. I am seeking some guidance as I navigate through this new territory. On my JSP page, there is a drop down list that needs to be populated with content when the page loads. To achieve this, I hav ...

Which is better: Embedding HTML in a Javascript source or using AJAX to fetch the HTML?

My application currently includes message boxes similar to those on Facebook. Although they are functioning well, I find myself increasingly dissatisfied with the way I am handling a specific aspect of these message boxes. Each message box consists of a t ...

Generating a unique bootstrap navigation bar using JSON data to achieve a unique and customized outcome

I have successfully created a bootstrap navbar using JSON data, but I am encountering an issue at one particular point. var data = { "India": [ { "type": "delhi", "link": "https://www.google.com" } ...

Animating back with a jQuery if statement

Is there a way to implement an if statement that triggers an animation when the right image reaches +400px, and then animates back to -400px upon hovering over the image? $('#left img').mouseenter(function() { $('#right img').animate ...

Breaking text with overflow-wrap and <br> tag

Hello, I have successfully implemented a content editable div. However, I am looking to automatically insert a <br> tag whenever the text overflows the width of the content-editable area. Essentially creating a line break whenever there is an overf ...

Embedding List Structure and Specific Properties

If I have a matrix, how can I demonstrate whether a given list nested within another list satisfies the following rule: For any three (or more) elements of the list, X([i][j])[k] = X[i]([j][k]) ? To clarify, you could think about this in terms of an ident ...

What is the specific character code assigned to the "Enter" key on a

Check out this code snippet: http://jsfiddle.net/YttKb/ In my javascript, I am trying to add a new line of text using utf-8 coding. Which character should I use to make a new line? It seems like \n only creates a line break, not a new line of text. ...

What is the best way to extract a JSON array from a JSON object?

In my ReactJS project, I am receiving a JSON object from a GET request and I need to extract key-value pairs from it. {"return":"Success", "Items": [ {"Name":"centracore", "Type":"rollover" ,  "Os":"Windows",  "Level":"1", "Language_Used":"Assembly", ...

What is the best way to combine two nearly identical arrays/objects using underscorejs or a similar library?

In the realm of lists, there exists an old list and a new one. The mission at hand is to combine both, even in the presence of newly added key-value pairs. var oldList = [{ id: 1, name: 'Michael', sex: 'male', goodlooking: 1 }, ...

How can I achieve unique spacing between rows in material-ui grid components?

What is the most effective method for creating spacing between specific rows in a grid using material-ui? Consider the following grid with spacing={0}: GridContainer row1 GridItem GridItem row2 GridItem GridItem row3 GridItem GridItem row4 Gr ...

Different Option for Anchor Tag When Javascript is Disabled

One interesting feature is the ability to set a different "href" attribute for an anchor tag when JavaScript is disabled. For instance: When JavaScript is enabled: <a href="#news">News</a> If JavaScript is not enabled: <a href="news.htm ...

What is the best way to enhance the data in my Firebase real-time database by combining it with a randomly generated ID?

I am facing an issue with sending data from a form to my database. It seems that when I use the .push() method, it creates a unique ID and stores my data under that ID. Now, I want to retrieve that data and add a new unique ID entry to it. However, I am un ...

Using Angular directives to dynamically add event listeners with the ng-repeat directive

I am currently working with a directive that includes event listeners for an element in the link function. For example: ... link: function(scope, element) { // this gives us the native JS object var el = element[0]; el.draggable = true; ...

iOS does not support webkit-transform functionality

I've been working on incorporating a navigation drawer into my Sencha Touch app by following this article. The animation mentioned in the article utilizes webkit-transform, which functions perfectly on Chrome and Android devices, but seems to be causi ...

Utilizing Dropzone for file uploads in Node.js, Express, and Angular

I'm running into a bit of trouble trying to get the file recognized on the server side with node.js. Especially when trying to access request data, such as req.files or req.body If anyone has any advice, here are some code snippets: HTML: <form ...

Is it possible to synchronize Vue data values with global store state values?

I need help updating my data values with values from store.js. Whenever I try the code below, I keep getting a blank page error. Here's how I have it set up in App.vue: data() { return { storeState: store.state, Counter: this.storeState.C ...

adding a JavaScript module to a handlebars template

I have a few different files that I'm working with: In the server.js file, I have the following code: app.get('/main/:id', function(req, res) { res.render('main', { products: products }); }) Within the main.hbs file, I have ...