Ember js - 从数组中删除重复项

时间:2018-03-23 15:11:14

标签: javascript arrays ember.js

我正在尝试清理验证脚本。

因此,如果上传的文件类型错误 - 就像图像而不是pdf。我需要警告说 - 上传了错误的文件类型,只接受了PDF格式。

https://jsfiddle.net/mf78otve/37/

所以验证字符串看起来像这样

"application/pdf, application/x-pdf, application/acrobat, applications/vnd.pdf, text/pdf, text/x-pdf"

但确实需要清理它 - pdf,x-pdf,vnd.pdf,pdf,x-pdf

然后删除重复项,然后删除pdf,x-pdf,vnd.pdf

var validations = "application/pdf, application/x-pdf, application/acrobat, applications/vnd.pdf, text/pdf, text/x-pdf";

console.log("validations", validations);

var res = validations.split("/");
console.log("res", res);


var uniqueArray = function(arrArg) {
  return arrArg.filter(function(elem, pos,arr) {
    return arr.indexOf(elem) == pos;
  });
};


console.log(uniqueArray(res));

2 个答案:

答案 0 :(得分:0)

使用Setsplitfiltermap

var output = [...new Set( //Use set to remove duplicates
     input.split(",") //split by comma
          .map(s => s.split("/")[1]) take out value after /
          .filter( s => s.includes( "pdf" ) ) //only keep the values having pdf in it
)];

<强>演示

var input = "application/pdf, application/x-pdf, application/acrobat, applications/vnd.pdf, text/pdf, text/x-pdf";

var output = [...new Set(input.split(",").map(s => s.split("/")[1]).filter( s => s.includes( "pdf" ) ))];

console.log( output )

答案 1 :(得分:0)

使用split然后map和finllay filter的组合

&#13;
&#13;
var validations = "application/pdf, application/x-pdf, application/acrobat, applications/vnd.pdf, text/pdf, text/x-pdf";

var result = validations.split`, `.map((a)=>a.split`/`[1]).filter((a,p,s)=>a.includes`pdf`&& s.indexOf(a)==p)

console.log(result)
&#13;
&#13;
&#13;