determining the arrangement of objects in an array when using the find method

I am providing the following code snippet:

var users = [
    {
        name: 'Mark',
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8fe2eefde4cfe2eee6e3a1ece0e2">[email protected]</a>',
        age: 28,
        address: 'England',
        val: true
},
{
    name: 'John',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f9939691978a9697b994989095d79a9694">[email protected]</a>',
    age: 25,
    address: 'USA'
    },
    {
        name: 'Tom',
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ccb8a3a18ca1ada5a0e2afa3a1">[email protected]</a>',
        age: 35,
        address: 'England'
    }];

let res = users.find(
      user => (user.name === 'John' || user.name === 'Tom'
      || user.val === true),
    );

console.log(res);

How can I prioritize searching by 'name', as currently the result is showing object with name Mark. I want to get the object with name John if it exists, or Tom, and if no names are found, then search by val.

Answer №1

Give it a shot

let result = users.find(
      person => (person.name === 'John' || person.name === 'Tom'
      || (!person.name && person.val === true)),
    );

Answer №2

Avoid using the Array.find method as it only returns one value. Instead, consider using a for...of loop to populate two arrays based on specific conditions:

let highPriority = [], lowPriority = [];
for (const item of items) {
    if (item.name === 'John' || item.name === 'Tom') highPriority.push(item);
    if (item.value) lowPriority.push(item);
}

let result = highPriority.length ? highPriority : lowPriority;

Answer №3

You are almost there, just switch .find() to .filter() and it will display all users that meet the specified criteria. There was a mistake with the name 'Johnk' instead of 'John', which is why it couldn't find the correct user due to the incorrect name and missing 'val' attribute.

var users = [
    {
        name: 'Mark',
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97faf6e5fcd7faf6fefbb9f4f8fa">[email protected]</a>',
        age: 28,
        address: 'England',
        val: true
},
{
    name: 'Johnk',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c262324223f23220c212d2520622f2321">[email protected]</a>',
    age: 25,
    address: 'USA'
    },
    {
        name: 'Tom',
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9beff4f6dbf6faf2f7b5f8f4f6">[email protected]</a>',
        age: 35,
        address: 'England'
    }];

let res = users.filter(
      user => (user.name === 'John' || user.name === 'Tom'
      || user.val === true),
    );

console.log(res);

Answer №4

Here is a sample code that might fulfill your requirements:

var users = [
  {
    name: "Mark",
    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bccfd3c9cec2d8cfccecd6ffc5cdd8fbc6cac8">[email protected]</a>",
    age: 28,
    address: "England",
    val: true
  },
  {
    name: "John",
    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="49170613131e073f38371a121ee25f5351">[email protected]</a>",
    age: 25,
    address: "USA"
  },
  {
    name: "Tom",
    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82b89fa09aa08db8b4a3adbbaeb597bab69e">[email protected]</a>",
    age: 35,
    address: "England"
  }
];

function findUser(names) {
  // utilizing `Array.reduce` to iterate through all names
  // and locate the first name in the `users` array
  var user = names.reduce((result, name) => {
    if (result) {
      return result;
    }
    return users.find(user => user.name === name) || null;
  }, null);
  
  // if user was not found, search for a user based on the value of `val`
  return user ? user : users.find(user => user.val);
}

var res1 = findUser(["John", "Tom"]);
var res2 = findUser(["Tom", "John"]);
var res3 = findUser(["Jeff"]);

console.log(res1);
console.log(res2);
console.log(res3);

References:

Answer №5

const findUserByName = users.find(user => (user.name === 'xyz')); //Find user by name

if(findUserByName == null)
{  
  const findUserByValue = users.find(user => ( user.val=== 'true')); //Find user by value
}

This code will work for both cases, insert true/false based on your requirements

Answer №6

Give this a shot - it will retrieve the value if no name is found in the record

var users = [
  {
      name: 'Mark',
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2dfd3c0d9f2dfd3dbde9cd1dddf">[email protected]</a>',
      age: 28,
      address: 'England',
      val: true
},
{
  name: 'John',
  email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="18727770766b77765875797174367b7775">[email protected]</a>',
  age: 25,
  address: 'USA'
  },
  {
      name: 'Tom',
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f5819a98b598949c99db969a98">[email protected]</a>',
      age: 35,
      address: 'England'
  }];
   
  function searchByNameOrValue(name, val){
    return users.filter(x=> x.name==name ? x : (x.val==val ? x : null))
  }
  console.log(searchByNameOrValue("Mark", true))

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

Looking for a comprehensive calculation that takes into account various input values?

I need to display the List Price at the bottom of the form so users are aware of the cost to list their item. Within a php file, I have defined price brackets. For example, if the listing price is £150.00, it falls between £100 and £199.99 and thus nee ...

Unsuccessful attempt at aborting an Ajax request

Currently, I have developed a basic live search feature using jQuery ajax to search through a JSON file on the server and display a list of events. The script is programmed to show a list of events that were previously displayed on the page if the search ...

The JavaScript feature designed for activating modal popups is only effective for the initial item

I am in the process of developing a clothing shopping website where the main page displays various clothing items. Each garment has an "Add to Cart" button that triggers a popup modal when clicked. However, I am encountering an issue where the modal only ...

When the Popover appears in ShadCN, the input field unexpectedly takes focus

This unique component incorporates both Popover and Input functionality from shadcn. An issue I have encountered is that when I click on the Input to trigger the Popover, the Input loses focus and the cursor moves away from it. Expected outcome: Upon c ...

Having difficulty with a script not functioning properly within an onclick button

In my script, I am using the following code: for (var i in $scope.hulls) { if ($scope.hulls[i].id == 1234) { console.log($scope.hulls[i]); $scope.selectedHullShip1 = $scope.hulls[i]; } } The code works fine outside of the onclick button, but fails to run ...

The router is unable to direct when an item is clicked

I am encountering an issue with my routing setup - when I click on an item in the list-item component, it does not successfully route to the detail-component. Here is a glimpse of my source code: product-list.component.html: <h1>Product List Compon ...

Comparison between SSD and HDD animation speed in web hosting environments

I am currently in search of a web hosting provider for a website I have created. The site features some performance-heavy animations, particularly due to a fullscreen slider with filter and scaling transitions. I need a provider that can ensure optimal per ...

Encountered an issue while trying to establish a connection between node.js and MongoDB

db connection error querySrv ENOTFOUND _mongodb._tcp.nodeapi.vlvom.mongodb.net (node:7720) UnhandledPromiseRejectionWarning: Error: querySrv ENOTFOUND _mongodb._tcp.nodeapi.vlvom.mongodb.net at QueryReqWrap.onresolve [as oncomplete] (dns.js:203:19) (Us ...

Arranging JSON Objects within an array or text

I am curious if it is possible to arrange the keys in a JSON object as an array based on their values. Here is the JSON object: { "p1": { "name": "*****", "age": "18" }, "p2": { ...

What steps are involved in creating a default toolbar for a material picker in a React application?

Looking for assistance with customizing the toolbar for material picker (v3) by adding a title inside the dialog. I successfully implemented this in the KeyboardDatePicker following a helpful thread (https://github.com/mui-org/material-ui-pickers/issues/11 ...

Combining Meshes in three.js LOD

I am searching for an efficient way to utilize the LOD Object from three.js (view example here). My concept involves creating an LOD method similar to the one outlined in chapter 2.1 (found here). The structure consists of 3 levels: a 3D model in close ...

Implement the maskmoney library in your input fields

In the form below, I am automatically adding inputs using a JavaScript function like this: $('.Preco1').maskMoney({ decimal: '.', thousands: ' ', precision: 2 }); $('.Preco1').focus(); $('#sub').maskMon ...

Using JavaScript, extract current date from an API data

Here is an example of how the data from my API appears: const data = [{ "id": "1", "name": "Lesley", "creationDate": "2019-11-21 20:33:49.04", }, { "id": "2", "name": "Claude", "creationDate": "2019-11-21 20:33:09.397", }, { "i ...

"Triggering an AJAX POST request with a click event, unexpectedly receiving a GET response for

Hello there! I am currently attempting to send an AJAX POST request when a button is clicked. Below is the form and button that I am referring to: <form class="form-horizontal" > <fieldset> <!-- Form Name --> <legend> ...

The feature of option display is not supported on Safari browser

I am facing an issue with the functionality of two dropdown menus. The options in the second dropdown are supposed to be shown based on the selection made in the first dropdown. While this feature works perfectly in Chrome, it seems to be malfunctioning i ...

Tips for executing a .exe file in stealth mode using JavaScript?

I am currently working on the transition of my vb.net application to JavaScript and I am facing a challenge. I need to find a way to execute an .exe file in hidden mode using JS. Below is the snippet from my vb.net code: Dim p As Process = New Pro ...

Tracking changes in values from an array of objects in Vue.js can be achieved by implementing a method that

Within my code, there is an array called addRows that holds a collection of objects. These objects are dynamically added when the user clicks on a specific button. Once added, these objects are then pushed into the addRows array for the user to fill in. ...

Mesh object circling in the opposite direction of the displayed image

Working on replicating a Flash website using Three.JS and facing difficulty in achieving desired functionality. The goal is to create button images that orbit around the center of the screen, stop when hovered over by the mouse, and open a different locat ...

The function data() is coming back as null

This is the code snippet I am working with: $.getJSON("link here", function (result) { $.each(result, function (i, value) { $('.usersOfGroupList').append($("<li id='userElement' data-userId='' ></li>") ...

I am experiencing an issue with my route where the Passport JWT req.user is unexpectedly undefined

Setting up JWT with my express app has been quite the challenge! Despite getting most of it working, I've encountered a strange issue. My register and login routes are generating valid tokens and authentication works fine in the '/users' rou ...