【问题标题】:Remove duplicates from multi-dimensional array. Numbers and number strings are equal从多维数组中删除重复项。数字和数字字符串相等
【发布时间】:2016-09-15 21:54:25
【问题描述】:

我已经差不多了,但不知道如何比较数字和数字字符串。

flattenAndUnique([["hello", "abc"], [true], ["abc"], [123, "123"]])
// should return
// ["hello", "abc", true, 123]

我把它弄平了,并且我有数字到数字/字符串到字符串的比较。

var flat = arr.reduce(function(arrA, arrB) {
    return arrA.concat(arrB);
});
var unique = flat.filter(function(el, pos) {
    return flat.indexOf(el) === pos;
});

【问题讨论】:

  • 123'123' 不一样。你会把true'true' 一样对待吗? 'True''TRUE' 一样怎么样? [] 是否等于 ''
  • 我在这个问题中对待他们的态度是一样的。所以 123 和 '123' 是相等的。真和“真”不是。 “真”和“真”会是。 [] 和 '' 不会。我也在寻找一种方法。我只是无法理解逻辑。
  • 这是别人给我的脑筋急转弯,我被难住了。

标签: types duplicates comparison-operators


【解决方案1】:

let input = [["hello", "abc"], [true], ["abc"], [123, "123"]]

// you're trying to do a horrible thing
// so you get a horrible function like this
const unsafeParseInt = x => {
  let int = Number.parseInt(x, 10);
  return Number.isNaN(int) ? x : int;
}

const concat = (x,y) => x.concat(y);
const flatten = xs => xs.reduce(concat, []);
const uniques = xs => xs.filter((x,pos) => xs.indexOf(x) === pos);

let output = uniques(flatten(input).map(unsafeParseInt));

console.log(output);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-08
    • 2018-11-21
    • 1970-01-01
    • 2012-09-15
    • 2017-12-30
    • 2016-01-06
    • 1970-01-01
    • 2018-06-09
    相关资源
    最近更新 更多