Reputation: 685
I need to create a function (in JS) that takes an array as an argument and returns new array by filtering it (argument) and leaving elements with repetitive characters.
identicalFilter(["aaaaaa", "bc", "d", "eeee", "xyz"]) // => ["aaaaaa", "d", "eeee"]
identicalFilter(["88", "999", "22", "5454", "31333"]) // => ["88", "999", "22"]
So far, I've come up with this code and really screwed up
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
Upvotes: 1
Views: 928
Reputation: 50326
You can use reduce
& every
. Inside the reduce
callback get the first character and then use every
to check if all elements are same
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"]))
Upvotes: 1
Reputation: 371019
How about using a regular expression instead? Match and capture the first character, then backreference that character as many times as needed until reaching the end of the string:
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"]
If you don't like regular expressions, you could also turn the string into an array and check that .every
one of its characters is the same as the first:
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"]
Upvotes: 1