Why is the startsWith function not returning the expected result in my code? What could be causing this issue?

I have a code snippet that sorts a list based on user input, but it fails if the user's input contains spaces. How can I modify the code to handle inputs with spaces without removing the spaces between characters? For example, if the user input is 'Man santra', the list should be sorted according to "Man".

 var users = [{
    name: 'Devgad Mango'
  },
  {
    name: 'Mantra santra'
  },
  {
    name: 'Prag Mango'
  },
  {
    name: 'Pirate aam Mango'
  }, {
    name: 'Mango raw'
  },
];

function search(input) {
  const matches = [];
  const remeinder = [];
  users.forEach(user => {
    user.name.startsWith(input) ?
      matches.push(user) :
      remeinder.push(user);
  });
  console.log(matches, remeinder)

  // now we sort the matches

  matches.sort((a, b) => {
    const aa = a.name.toLowerCase();
    const bb = b.name.toLowerCase();
    if (aa < bb) {
      return -1;
    }
    if (aa > bb) {
      return 1;
    }
    return 0;
  });

  console.log(matches);
  // now we want to push the remeinders to the end of the sorted array.


  matches.push(...remeinder);

  console.log(matches);
  console.log(input);
}
const str = "*-*+&^%$#@!/\Man santra*";
var output = (str.replace(/[\/\\#@^!,+()&$~%.'":;*?`<>{}-]/g, ""));


search(output);

Answer №1

To determine if a name exists in the variable, utilize user.name.includes(). There is no need to eliminate spaces; simply input the search term into the function and it will return any matches containing that word.

var users = [{
    name: 'Devgad Mango'
  },
  {
    name: 'Mantra santra'
  },
  {
    name: 'Prag Mango'
  },
  {
    name: 'Pirate aam Mango'
  },
  {
    name: 'Mango raw'
  },
];

function search(input) {
  const matches = [];
  const remeinder = [];
  users.forEach(user => {
    user.name.includes(input) ?
      matches.push(user) :
      remeinder.push(user);
  });
  
  // sorting the matches
  matches.sort((a, b) => {
    const aa = a.name.toLowerCase();
    const bb = b.name.toLowerCase();
    if (aa < bb) {
      return -1;
    }
    if (aa > bb) {
      return 1;
    }
    return 0;
  });

  console.log(matches);
  // pushing the remainders to the end of the sorted array.
  matches.push(...remeinder);
  console.log(matches);
}
const str = "Mango";
search(str);

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

The definitive method for resolving synchronization problems between Protractor and Angular

The Issue at Hand: We recently encountered a common error while attempting to open a specific page in our application during a Protractor end-to-end test: Error: We timed out waiting for asynchronous Angular tasks to complete after 50 seconds. This cou ...

Challenges encountered when retrieving parameters from union types in TypeScript

Why can't I access attributes in union types like this? export interface ICondition { field: string operator: string value: string } export interface IConditionGroup { conditions: ICondition[] group_operator: string } function foo(item: I ...

modifying the identification value in HTML and then reverting it

Although this may seem like messy code, I'm really in need of assistance with a problem that has stumped me. Currently, I am working on an E-shop project where I have modals for displaying products. Within these modals, there is a button that allows u ...

Is it possible for GSON to perform deserialization in a case-insensitive manner?

While prototyping the communication between a .NET desktop app and a Java server using REST with JSON posts, a case-sensitivity issue has arisen. The .NET objects have their properties in Pascal Casing (as is standard for .NET), such as: Symbol, EntryValue ...

Obtain a JSON file using API in R and transform it into a dataframe

I've been attempting to download the JSON file from the NASDAQ request URL using R, but I haven't had any luck. While I have managed to come up with a solution in Python, my goal is to find a way to do it in R instead. I contacted the NASDAQ hel ...

Identifying the moment a member receives a role using my Discord bot built with discord.js

I am currently working on detecting when a user is assigned a specific role on a server. Here is the code I have been using: // Require the required discord.js classes const { token } = require('./config.json'); // Create a new client instance ...

When provided with varied inputs, new Date() yields distinct values for various time zones

var date1 = "2015-03-29"; console.log(new Date(date1)); //Output:Sun Mar 29 2015 05:30:00 GMT+0530 (India Standard Time) var date2 = "1869-12-31"; console.log(new Date(date2)); //Output:Fri Dec 31 1869 05:53:20 GMT+0553 (India Standard ...

What is causing the ajax code to malfunction?

I am new to ASP MVC and trying to create a login form using AJAX. I have written a JsonResult in the controller to check the username and password, but for some reason it is not working. Here is my controller code: public ActionResult login() { ...

React code displaying misalignment between label and input

Can you help me align my URL and https:// on the same margin? https://i.sstatic.net/hxkkC.png <div className="card"> <div className="card-body"> <div className="form-group col-12"> <label cla ...

Attempting to submit a form to Mailchimp with Vue.js and Axios causes a CORS error to occur

In my Vue.js application, I have a feature that sends email data from a form to Mailchimp using the Axios library. I recently learned that in order to bypass CORS restrictions when posting to Mailchimp's URL, I need to use the post-json version and a ...

Discord.js version 13 encountered an issue where it is unable to access properties of undefined while

Having trouble with creating a warn system that just won't work! I've tried various solutions but nothing seems to be fixing it. Would greatly appreciate any help! Error Log: [FATAL] Possibly Unhandled Rejection at: Promise Promise { <reje ...

Try out a Vue.js Plugin - A Comprehensive Guide

Currently, I am delving into the world of Vue.js. In my journey, I have crafted a plugin that takes the form of: source/myPlugin.js const MyPlugin = { install: function(Vue, options) { console.log('installing my plugin'); Vue.myMetho ...

What is the process for transmitting images from React Native to native modules?

Challenge I am facing an issue trying to send an array of locally saved images from the JavaScript side (stored in an assets folder) to both iOS and Android native sides. The native code processes the images and returns a new image successfully when using ...

Enhance your Rails application by dynamically updating table cells with Ajax, eliminating the need for

In my index.html.erb file, I have set up one form and one table. Using Ajax allows me to submit the form without any redirects. <%= form_for approval, remote: true do |f| %> <%= f.check_box :pass %> <%= f.submit%> <% end %> My ...

What is the technique for combining a string and an HTML element using literal values?

Trying to merge text with a hyperlink: const myText = `${t('privacyTxt')}` + `${<a>{t('privacyLink')}</a>}`; output: If you want to know more about our data processing, check out our[object Object] What else do I need ...

Unable to upload any further verification documents to Stripe Connect bank account in order to activate payouts

Query - Which specific parameters should I use to generate the correct token for updating my Stripe bank account in order to activate payouts? I've attempted to activate payouts for my Stripe bank account by using a test routing and account number (t ...

Adjust the HTML content prior to displaying it to prevent any flickering

Is there a way to run code before the page is rendered, such as updating dates or converting text to HTML, without causing flickering when reloading multiple times? How can I ensure the code runs as it's drawn instead of waiting until the end to redra ...

Is it possible to rename a project and package?

I'm currently working on an Android app called "English SMS Collection" that's available in the Google Play store. I now want to expand by adding a Hindi language version of the app. What changes do I need to make to the previous APK file? How ca ...

Tips for formatting input boxes on the client side

Q: How can I format my textbox so that when a user enters a number, such as one, it will be displayed as 0000001? The goal is to have any number entered be shown in 7-digit format. ...

Is there a way to dynamically include an attribute using VueJS?

Is there a way in Vue to dynamically add an attribute, not just the value of an attribute using v-bind? I am aware that I can set a value to an attribute dynamically with v-bind, but I would like to add the attribute itself based on a condition. Something ...