【问题标题】:How to split strings inside of an array in JavaScript (to get first names from full names)如何在 JavaScript 中拆分数组内的字符串(从全名中获取名字)
【发布时间】:2019-04-08 16:18:02
【问题描述】:

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

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(),但还没有能够破解它......

【问题讨论】:

  • 空间分割,返回第一个元素...return person.name.split(' ')[0]
  • 当我第一次开始编程时,Jane 大约 23 岁 :D 感谢您保持他们的年龄,哈哈

标签: javascript arrays string foreach split


【解决方案1】:

您可以使用Array.map()String.split() 来解决这个问题。基本上,您需要将每个fullname 映射到first name,因此在每个space 上使用splitspace 字符,我们可以获得一个名称数组,该数组的第一个元素将是@ 987654330@.

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

【讨论】:

  • 单线:input.map(x =&gt; x.split(' ')[0])
【解决方案2】:

在您的地图函数中尝试 var names = person.name.split(" ");并返回名称[0];

【讨论】:

  • 就是这样! @charlietfl 在上面的 cmets 中说了同样的话:“在空间上分割,返回第一个元素......返回 person.name.split(' ')[0]”两者都很好。
【解决方案3】:

如果您被允许使用 forEach 属性,您可能希望:

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

否则您将不得不学习如何使用while 循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2012-10-20
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    相关资源
    最近更新 更多