如果我有一个数组:
["one", "two", "three", "thee", "four", "fowr"]
一个比较字符串匹配可能性的函数:
stringCompare('testing', 'testign')
输出0.7
根据stringCompare()
函数的结果过滤数组的最佳方法是什么 - 比如删除任何得分为0.8或以上的值,以便生成的数组为:
["one", "two", "three", "four"]
答案 0 :(得分:2)
您也可以使用lodash
:
const array = ['one', 'two', 'two', 'three', 'four', 'three', 'two'];
const isSimilar = (s1, s2) => s1 == s2; // Switch this for your stringCompare function
const result = _.uniqWith(array, isSimilar);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
答案 1 :(得分:0)
将reduce
,forEach
与stringCompare
功能组合使用(评论内联)
var stringCompare = (str1, str2) => Number(str1 == str2); //assume for the purpose of this function
//fn to get duplicate values of a particular value in an array
var getDups = (s, i, arr) => arr.slice(i + 1).filter((it, ind) => stringCompare(s, it) > 0.8);
//fn to remove duplicate values from array
var removeDups = (arr, dupArr) => dupArr.forEach(s => arr.splice(arr.indexOf(s), 1));
var arr = ["one", "two", "three", "three", "four", "four"];
var output = arr.reduce( (acc, c, i, arr) =>
(removeDups(acc, getDups(c, i, arr)), acc), //remove duplicates from accumulator
arr);//initialize with input arr
console.log(output);
&#13;
答案 2 :(得分:0)
您可以使用filter()
方法,在内部,您可以使用every()
方法中的部分先前元素,并使用<= 08
方法检查每个元素是否与过滤器循环中的当前元素类似const arr = ["one", "two", "three", "thee", "four", "fowr"]
function compare(a, b) {
let found = 0;
a.split('').forEach(e => b.includes(e) && found++);
return found / a.length <= 0.8;
}
const result = arr.filter(function(a, i) {
const prev = arr.slice(0, i);
return prev.every(b => compare(a, b))
})
console.log(result)
。 / p>
time id el conn column1 column2 column3
2018-02-11 14:00:00 1 a 12 8 5 NaN
2018-02-11 14:00:00 1 a 12 1 NaN NaN
2018-02-11 14:00:00 1 a 12 3 7 NaN
2018-02-11 14:00:00 1 a 12 4 12 NaN
2018-02-11 14:00:00 2 a 5 NaN 5 5
2018-02-11 14:00:00 2 a 5 NaN 3 2
2018-02-11 14:00:00 2 a 5 NaN NaN 6
2018-02-11 14:00:00 2 a 5 NaN 7 NaN
&#13;