Peoray
Peoray

Reputation: 1925

How to get the Initials of a Name from an Object

My code doesn't work. I need feedback and an efficient way to return the Initials of the First and Last name that matches the id passed to the function.

var contactList = [
    {
    "id": 'e3d46de8c7194cb1a32275195c15dc07',
    "name": 'Niels Bohr',
    "num_messages": 62,
    },
    {
    'id': '7064c3f9c99743b2838bbd8eacafe0d6',
    "name": 'Max Planck',
    "num_messages": 15,
    },
    {
    "id": 'b19e575a0d3f4151a1391452d8a47a44',
    "name": 'Jane Goodall',
    "num_messages": 20,
    },
    {
    "id": '17d9d0908f454253b5337e8c1ef4b564',
    "name": "Caroline Herschel",
    "num_messages": 3,
    },
]

function getInitials(id){
    // find the user object
    for (let u of contactList) {
        if (u["id"] == id){
            var initials = ''
            names = u.name.split(' ')
            for(var i; i < names.length; i++){
                initials += names[i][0]
            }
            // return the initials
            return initials
        }
    }
}

Upvotes: 1

Views: 1196

Answers (7)

sergey krupnov
sergey krupnov

Reputation: 16

    You have bag :
    ` for(var i; i < names.length; i++){
       initials += names[i][0]
      } `   
     1.i have to be initelased var i = 0;            

besides of this your code is working

Upvotes: 0

jo_va
jo_va

Reputation: 13973

Here is a succint way to do it with filter, map, shift and a regex in a single chain of operations. The technique will work with any number of spaces, see the example below and will return undefined if the contact id is not found.

First, you filter the array for the correct id, this returns an array (could be empty) on which you map to extract the initials with String.match, the regex and Array.join. You then shift the first element out to get the result, shift won't raise an error if there is no element and will simply return undefined.

Here are two possible regex for extracting the initials:

  • /\b(\w)/g
  • /(?<=(\s+|^))(\w)/g

The first regex uses \b to match word boundaries while \w will match any word character, so the regex \b(\w) will capture the first character of every word. This regex will fail when the names are separated with dashes, as the dash will count as a word separator.

The second regex will match every first word character using the positive lookbehind (?<=(\s+|^)) which checks for spaces or the beginning of the string.

const contactList = [{
  "id": 'e3d46de8c7194cb1a32275195c15dc07',
  "name": '   Niels        Bohr',
  "num_messages": 62,
}, {
  'id': '7064c3f9c99743b2838bbd8eacafe0d6',
  "name": 'Max Planck    ',
  "num_messages": 15,
}, {
  "id": 'b19e575a0d3f4151a1391452d8a47a44',
  "name": '  Jane Goodall',
  "num_messages": 20,
}, {
  "id": '17d9d0908f454253b5337e8c1ef4b564',
  "name": "Caroline Herschel",
  "num_messages": 3,
}];

function getInitials(id) {
  return contactList
    .filter(contact => contact.id === id)
    .map(contact => contact.name.match(/(?<=(\s+|^))(\w)/g).join(''))
    .shift();
}

console.log(getInitials('17d9d0908f454253b5337e8c1ef4b564'));
console.log(getInitials('b19e575a0d3f4151a1391452d8a47a44'));
console.log(getInitials('7064c3f9c99743b2838bbd8eacafe0d6'));
console.log(getInitials('e3d46de8c7194cb1a32275195c15dc07'));
console.log(getInitials('123'));

Upvotes: 1

Maheer Ali
Maheer Ali

Reputation: 36584

First of all find the the item whose id matches given id using find(). Then split() its name and map it to its name[0] and then join()

var contactList = [
    {
    "id": 'e3d46de8c7194cb1a32275195c15dc07',
    "name": 'Niels Bohr',
    "num_messages": 62,
    },
    {
    'id': '7064c3f9c99743b2838bbd8eacafe0d6',
    "name": 'Max Planck',
    "num_messages": 15,
    },
    {
    "id": 'b19e575a0d3f4151a1391452d8a47a44',
    "name": 'Jane Goodall',
    "num_messages": 20,
    },
    {
    "id": '17d9d0908f454253b5337e8c1ef4b564',
    "name": "Caroline Herschel",
    "num_messages": 3,
    },
]
function getInitials(id){
    let obj = contactList.find(item => item.id === id);
	return obj && obj.name.split(' ').map(a => a[0]).join('');
}
console.log(getInitials('7064c3f9c99743b2838bbd8eacafe0d6'))
console.log(getInitials('17d9d0908f454253b5337e8c1ef4b564'))
console.log(getInitials('b19e575a0d3f4151a1391452d8a47a44'))
console.log(getInitials('0'))

Upvotes: 2

Ashish
Ashish

Reputation: 4330

A simple and one-liner approach using Array.reduce and Array.find This function will return undefined if id is not present.

var contactList = [
    {
    "id": 'e3d46de8c7194cb1a32275195c15dc07',
    "name": 'Niels Bohr',
    "num_messages": 62,
    },
    {
    'id': '7064c3f9c99743b2838bbd8eacafe0d6',
    "name": 'Max Planck',
    "num_messages": 15,
    },
    {
    "id": 'b19e575a0d3f4151a1391452d8a47a44',
    "name": 'Jane Goodall',
    "num_messages": 20,
    },
    {
    "id": '17d9d0908f454253b5337e8c1ef4b564',
    "name": "Caroline Herschel",
    "num_messages": 3,
    },
]

function getInitials(id){
  //using .find to find the element in the array
  const contact = contactList.find(contact => contact.id === id) 
  //cross checking if id is present and for that id name key is present and then using reduce function to get initials.
  return contact && contact.name && contact.name.split(' ').reduce((initial, name) => initial + name[0], '')
}

console.log(getInitials('b19e575a0d3f4151a1391452d8a47a44'))  //JG

console.log(getInitials('random'))  //undefined

Upvotes: 0

Prasad Telkikar
Prasad Telkikar

Reputation: 16079

You can try below code

var contactList = [
    {
    "id": 'e3d46de8c7194cb1a32275195c15dc07',
    "name": 'Niels Bohr',
    "num_messages": 62,
    },
    {
    'id': '7064c3f9c99743b2838bbd8eacafe0d6',
    "name": 'Max Planck',
    "num_messages": 15,
    },
    {
    "id": 'b19e575a0d3f4151a1391452d8a47a44',
    "name": 'Jane Goodall',
    "num_messages": 20,
    },
    {
    "id": '17d9d0908f454253b5337e8c1ef4b564',
    "name": "Caroline Herschel",
    "num_messages": 3,
    },
]

//here constant is your id which you passed in if condition
var str = contactList.find(x => x.id =='17d9d0908f454253b5337e8c1ef4b564').name.split(' ');
var result =""
for(var s of str)
   result += s.substr(0, 1)
   
console.log("Initals of \""+str+"\" is " + result);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386680

You could find the object, get the name and build the initals.

function getInitials(array, id) {
    var temp = array.find(o => o.id === id);
    return temp && temp.name.split(' ').map(([c]) => c).join('');
}

var contactList = [{ id: 'e3d46de8c7194cb1a32275195c15dc07', name: 'Niels Bohr', num_messages: 62 }, { id: '7064c3f9c99743b2838bbd8eacafe0d6', name: 'Max Planck', num_messages: 15 }, { id: 'b19e575a0d3f4151a1391452d8a47a44', name: 'Jane Goodall', num_messages: 20 }, { id: '17d9d0908f454253b5337e8c1ef4b564', name: "Caroline Herschel", num_messages: 3 }];

console.log(getInitials(contactList, 'b19e575a0d3f4151a1391452d8a47a44'));
console.log(getInitials(contactList, '000'));

Upvotes: 1

&#193;lvaro Touz&#243;n
&#193;lvaro Touz&#243;n

Reputation: 1230

try this, could be your needed?

var contactList = [
    {
    "id": 'e3d46de8c7194cb1a32275195c15dc07',
    "name": 'Niels Bohr',
    "num_messages": 62,
    },
    {
    'id': '7064c3f9c99743b2838bbd8eacafe0d6',
    "name": 'Max Planck',
    "num_messages": 15,
    },
    {
    "id": 'b19e575a0d3f4151a1391452d8a47a44',
    "name": 'Jane Goodall',
    "num_messages": 20,
    },
    {
    "id": '17d9d0908f454253b5337e8c1ef4b564',
    "name": "Caroline Herschel",
    "num_messages": 3,
    },
]

function getInitials(id){
    // find the user object
    for (let u of contactList) {
        if (u["id"] == id){
            var initials = ''
            names = u.name.split(' ')
            console.log(names.length);
            for(var i=0; i< names.length; i++){
            
              initials+=' ' + names[i].charAt(0);
            }
            // return the initials
            console.log(initials, 'pop');
            return initials
        }
    }
}
getInitials('17d9d0908f454253b5337e8c1ef4b564');

Upvotes: 0

Related Questions