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

Using dot notation for event handlers in Vue.Js is a handy technique

I am currently developing a Single Page Application (SPA) using Vue.js 3 and Bootstrap 5. On the main page, I have implemented the Bootstrap Offcanvas element with code that closely resembles the one provided in the documentation. The structure of the off ...

SequelizeDatabaseError: The operation could not be executed as there is no operator that allows for

I am attempting to create a join between two tables using UUIDs (also have IDs), and the relationships between these tables are quite complex... However, I encounter an error when running the query. The first table is named users, with its UUID labeled a ...

Integrate Thymeleaf properties seamlessly into JavaScript code

I am attempting to embed a property from Spring's application.properties into JavaScript. It is working properly with the following code: <h1 th:utext="${@environment.getProperty('key')}"></h1> However, it returns null with th ...

Pass along complex JSON data structure from the view to the model

Is there a way to efficiently send Nested JSON data from the view to the model? Most solutions I've found don't account for variable keys within the object. Here's an example of the JSON object: "Login": { "userId": "harshal.bulsara", ...

Pagination with Arrays

I'm currently working on a script that I want to convert into pagination. Can anyone provide assistance with this task? $values = json_decode(file_get_contents('data/blogs.json')); foreach ($values as $data){ $data = clone (object)array ...

Having issues with Vue.js when using Vue-strap Radio Buttons

While developing my web application with vue.js, I encountered an issue with radio buttons when I switched to using bootstrap style. I understand that I need to use vue-strap for proper data binding with bootstrap styled radio buttons in vue.js, but I am s ...

Mysterious failure of JavaScript regular expression when encountering the term "tennis"

We developed a JavaScript script to detect duplicates or potential duplicates, but it seems to have some issues with certain words like "tennis." The script functions correctly in most cases, but fails when analyzing phrases related to the word "tennis" fo ...

I'm puzzled as to why I have to encode the path parameter twice in order for the REST call to properly handle special characters

I have a challenge with a REST call that fetches a product's ingredients using the product name as the path variable. I allow for any character to be used, and I know I need to use encodeURIComponent(name) to encode characters such as "/" to prevent m ...

What is the best way to determine in component.html whether the column type is equal to 1 to show the label text "Active,"

Having trouble checking the value of an object named ReportControl. If the column type is 1, display the label "active"; otherwise, display the label "not active" on reportcomponent.html. The data for the ReportControl object is as follows: {"reportId": ...

Incorporate the key as a prop within a Child Component in a React application

I am trying to display a list of elements in React, where the key of each element is used as an index in front of the item. However, when I try to access props.key, it just returns undefined. Does anyone have any suggestions on how to access the key proper ...

Alternative to updating object coordinates in Fabric JS 1.7.9 - seeking solutions for migration challenges

Update: JSFiddle: https://jsfiddle.net/Qanary/915fg6ka/ I am currently working on implementing the `curveText` function (found at the bottom of this post). It was functioning properly with `fabric.js 1.2.0`, but after updating to `fabric.js 1.7.9`, I not ...

Using Vue.js: Is there a way to apply scoped CSS to dynamically generated HTML content?

Summary: I'm struggling to apply scoped CSS styling to dynamically generated HTML in my Vue component. The generated HTML lacks the necessary data attribute for scoping, making it difficult to style with scoped CSS rules. Details: In a function cal ...

Positioning elements at the bottom of the container

There is a dilemma that only those in the world of web development will understand. Beware! I have envisioned a layout for a website I am constructing. The concept involves tilted <hr/> elements on the page, with text wrapping around them (refer to ...

Highchart displays results for each individual line without the use of commas

I am interested in creating a chart using Highchart with three lines. The first two lines will display data similar to [4.12, 3.34, 5.45] / [3.45, 5.45, 3.23], while the third line should be displayed without any commas, showing results like [7, 4, 2]. Can ...

How can I prevent my JSON object from serializing .NET nulls as "null" for object members?

I am currently utilizing WebMethods to retrieve an array of a custom class. When this array is returned from a Jquery .ajax call, it gets serialized into a JSON object that can be utilized with Javascript in my ASP.NET application. The issue I am facing is ...

Struggling to make a form submit work with AngularJS and a Bootstrap datetime picker

Struggling to create a post and include name and datetime using a bootstrap datetimepicker. After selecting the datetime and clicking add, nothing happens. However, if I manually type in the field and click add, it submits successfully. Despite reading up ...

Trouble with pinch zoom functionality in a Vue component

I have a Vue component that allows me to zoom in on an image using the mouse wheel, but I'm experiencing strange behavior with pinch zoom. When I place two fingers far apart on the screen, it zooms in significantly, and when I bring them closer togeth ...

Providing structured Express app to deliver HTML and JavaScript content

Currently, I am working with Express and facing a seemingly simple challenge. Here is the structure of my directories: |-config |---config.js |---routes.js |-server.js |-scripts |---controllers |------controllers.js |---directive ...

Is there a way to verify the existence of a user in mongoose?

Currently, I am attempting to verify the existence of a user with the code below: const userExist = await User.find({ username: req.body.username }); if (userExist) return res.status(400).send({ message: "User already exists" }); However, eve ...

Step-by-step guide on achieving a radiant glow effect using React Native

I am looking to add a glowing animation effect to both my button and image elements in React Native. Is there a specific animation technique or library that can help achieve this effect? While I have this CSS style for the glow effect, I am uncertain if ...