过滤重复的字符串

问题描述 投票:0回答:1

我需要创建一个函数(在JS中),将一个数组作为参数,并通过过滤它(参数)并留下带有重复字符的元素来返回新的数组。

identicalFilter(["aaaaaa", "bc", "d", "eeee", "xyz"]) // => ["aaaaaa", "d", "eeee"]
identicalFilter(["88", "999", "22", "5454", "31333"]) // => ["88", "999", "22"]

到目前为止,我已经想出了这段代码,但真的搞砸了。

function identicalFilter(arr) {
    let newArr = [];
    let tempArr = arr.forEach(key => {
        return key.split('');
    });
    for (let i = 0; i < tempArr.length; i++){
        let count = 0;
        for (let k = 0; k < tempArr[i].length; k++){
            if (tempArr[i][0]===tempArr[i][i]) {
                count++;
            }
            if (count === temArr[i].length){
                newArr.push(tempArr[i]);
            }
        }
    }
    return newArr;
}

SOS

javascript
1个回答
1
投票

你可以使用 reduce &amp; every. 内 reduce 回调得到第一个字符,然后用 every 检查所有元素是否相同

function identicalFilter(arr) {
  if (arr.length === 0) {
    return [];
  }
  return arr.reduce((acc, curr) => {
    let firstChar = curr.charAt(0);
    let isSame = curr.split('').every(item => item === firstChar);
    if (isSame) {
      acc.push(curr)
    }
    return acc;
  }, [])
}





console.log(identicalFilter(["aaaaaa", "bc", "d", "eeee", "xyz"]))
console.log(identicalFilter(["88", "999", "22", "5454", "31333"]))

1
投票

用正则表达式来代替如何?匹配并捕获第一个字符,然后根据需要多次反向引用该字符,直到到达字符串的末端。

const identicalFilter = arr => arr.filter(
  str => /^(.)\1*$/.test(str)
);

console.log(identicalFilter(["aaaaaa", "bc", "d", "eeee", "xyz"])) // => ["aaaaaa", "d", "eeee"]
console.log(identicalFilter(["88", "999", "22", "5454", "31333"])) // => ["88", "999", "22"]

如果你不喜欢使用正则表达式 你也可以把字符串变成一个数组 然后检查一下... .every 其中一个字与第一个字相同。

const identicalFilter = arr => arr.filter((str) => {
  const arr = [...str];
  const firstChar = arr.shift();
  return arr.every(char => char === firstChar);
});

console.log(identicalFilter(["aaaaaa", "bc", "d", "eeee", "xyz"])) // => ["aaaaaa", "d", "eeee"]
console.log(identicalFilter(["88", "999", "22", "5454", "31333"])) // => ["88", "999", "22"]
© www.soinside.com 2019 - 2024. All rights reserved.