示例
commentsArray = ["John?mycomment284","Sophie?mycomment938","John?mycomment595"]
结果:commentsArray = ["John?mycomment284","Sophie?mycomment938"]
所有注释均以“?”与名称分开
如何每人只发表一条评论?并从同一个人中删除所有其他人。
答案 0 :(得分:2)
const commentsArray = ["John?mycomment284","Sophie?mycomment938","John?mycomment595"]
const res = Object.values(commentsArray.reduce((acc, cur) => acc[cur.split('?')[0]] ? acc : (acc[cur.split('?')[0]] = cur, acc), {}))
console.log(res)
答案 1 :(得分:0)
使用过滤器:
const commentsArray = ["John?mycomment284","Sophie?mycomment938","John?mycomment595"]
let people=[];
let firstComment = commentsArray.filter(comment => {
let person = comment.split("?")[0];
if (people.indexOf(person) ==-1) {
people.push(person);
return comment;
}
});
console.log(
firstComment
)