t .
t .

Reputation: 5

How to split strings inside of an array in JavaScript (to get first names from full names)

My assignment is to print the first names of all individuals from a data set that fit a specific category; however, the data set is an array of objects that provides the full name as a string, e.g.:

var dataSet = [ 
    {
        "name": "John Doe",
        "age": 60,
        "math": 97,
        "english": 63,
        "yearsOfEducation": 4
    },
    {
        "name": "Jane Doe",
        "age": 55,
        "math": 72,
        "english": 96,
        "yearsOfEducation": 10
    }
]

I cannot use any array type built-in functions except filter(), map(), and reduce().

The last chunk of my code (to get names from the array of objects "dataSet") looks like:

var youngGoodMath = dataSet.filter(function(person){
    return person.age < avgAge && person.math > avgMath;
  });

  var yGMname = youngGoodMath.map(function (person){
    return person.name;
  });

console.log(yGMname);

which produces an array of strings that looks something like:

["Jane Doe", "John Doe", "Harry Potter", "Hermione Granger"]

I need to find a way to produce:

["Jane", "John", "Harry", "Hermione"]

I suspect the answer lies in using .forEach and .Split(), but haven't been able to crack it yet...

Upvotes: 0

Views: 740

Answers (3)

Bekim Bacaj
Bekim Bacaj

Reputation: 5955

in case you are allowed to use the forEach property, you might want to:

dataSet.forEach( function( x ) { console.log( x.name.match( /\w+/)+"" ) } );

otherwise you'll have to learn how to use the while loop.

Upvotes: 0

Shidersz
Shidersz

Reputation: 17190

You can use Array.map() and String.split() to solve this. Basically, you need to map every fullname to the first name, so using split by space character on every fullname we can get an array of names, and the first element of that array will be the first name.

const input = ["Jane Doe", "John Doe", "Harry Potter", "Hermione Granger"];

let res =  input.map(name =>
{
    [first, ...rest] = name.split(" ");
    return first;
});

console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Another alternative is to use String.match() with a positive lookahead regular expression, i.e, match a starting sequence of characters that are followed by a space.

const input = ["Jane Doe", "John Doe", "Harry Potter", "Hermione Granger"];
let res =  input.map(name => name.match(/^.*(?=\s)/)[0]);
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Upvotes: 2

G. Tudor
G. Tudor

Reputation: 28

In your map function try var names = person.name.split(" "); and return names[0];

Upvotes: 0

Related Questions