如何在JavaScript中的数组内拆分字符串(从全名中获取名字)

时间:2019-04-08 16:18:03

标签: javascript arrays string foreach split

我的任务是打印适合特定类别的数据集中所有个人的名字;但是,数据集是一个对象数组,它以字符串形式提供全名,例如:

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

除filter(),map()和reduce()之外,我不能使用任何数组类型的内置函数。

我的代码的最后一块(从对象数组“ dataSet”中获取名称)如下所示:

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);

产生一个字符串数组,看起来像:

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

我需要找到一种生产方法:

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

我怀疑答案在于使用.forEach和.Split(),但还无法破解...

3 个答案:

答案 0 :(得分:2)

您可以使用Array.map()String.split()来解决此问题。基本上,您需要将每个fullname映射到first name,因此在每个split上使用spacefullname字符,我们可以获得一个名称数组,并且该数组的第一个元素将是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;}

另一种替代方法是将String.match()positive lookahead正则表达式配合使用,即匹配起始字符序列,后跟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;}

答案 1 :(得分:0)

在您的map函数中,尝试var names = person.name.split(“”);并返回名称[0];

答案 2 :(得分:0)

在允许您使用forEach属性的情况下,您可能需要:

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

否则,您将必须学习如何使用while循环。