I want to remove special characters and letters from an array and calculate the sum of the remaining integers in the array, in JavaScript.
const arr = ["13,d42", "d44f2", "1g5", "1c42"];
let numbersOnly = (val) => {
if (typeof val === "number") {
// replace number with string to get only string values in an array.
return val;
} else {
let temp = val.split("");
// document.write(temp);
let newArr = [];
for (let i = 0; i < temp.length; i++) {
if (typeof temp[i].parseInt() === 'number') {
document.write(i)
newArr.push(temp[i]);
}
}
// return newArr;
// document.write(newArr)
}
};
let numbers = arr.map(numbersOnly).reduce((partialSum, a) => partialSum + a, 0);
document.write(numbers);
reduce over the array. For each string find the numbers using match with a simple regular expression, then join that array into one string, and then coerce it to a number.
const arr = ['13,d42', 'd44f2', '1g5', '1c42'];
const sum = arr.reduce((sum, str) => {
const num = Number(str.match(/\d/g).join(''));
return sum + num;
}, 0);
console.log(sum);
Sidenote: you probably shouldn't be using document.write:
⚠ Warning: Use of the document.write() method is strongly discouraged.
Can this help you?
const arr = ["13,d42", "d44f2", "1g5", "1c42"];
const onlyNumbers = arr
.map((value) => value.replace(/[^0-9]/g, "")) // get just numbers
.reduce((pv, cv) => parseInt(pv) + parseInt(cv)); // add up the numbers
console.log(onlyNumbers);
I have created getNumber which accepts a string as parameter and return the number which its contain.
For example if we pass "13,d42" so it will gonna return us 1342 as number.
And my another function getTotalSum will call the function for all the string and do some of all numbers which getNumber return;
const arr = ["13,d42", "d44f2", "1g5", "1c42"];
const getNumber = (numberString) => {
let numberRes = '';
for(let i = 0; i< numberString.length;i++){
if(!isNaN(parseFloat(numberString[i]))){
numberRes += numberString[i];
}
}
return parseFloat(numberRes);
}
const getTotalSum = (arr) => {
let sum = 0;
arr.forEach(el =>{
sum += getNumber(el)
});
return sum;}
The solution is quite simple if you only want to parse each individual string in the array.
const arr = ["13,d42", "d44f2", "1g5", "1c42"];
const numbersOnly = (val) => {
const re = /\D/g;
return parseInt(val.replaceAll(re, ""));
}
let numbers = arr.map(numbersOnly).reduce((partialSum, a) => partialSum + a, 0);
console.log(numbers);
But more importantly what answer are you desiring? Are you treating "13,d42" as 13,42 or 1342?
Use Array#map with a regular expression to replace all special characters and letters then use + to convert from string to numeric. Finally, use Array#reduce to add the numbers to get the sum.
const arr = ["13,d42", "d44f2", "1g5", "1c42"],
output = arr
.map(item => +item.replace(/[^\d]+/g,''))
.reduce(
(sum,item) => sum + item,0
);
console.log( output );
Alternatively ...
You can do it without Array#map as follows:
const arr = ["13,d42", "d44f2", "1g5", "1c42"],
output = arr
.reduce(
(sum,item) => sum + +item.replace(/[^\d]+/g,''),0
);
console.log( output );
1941 is correct answere. because "13,d42" is first element of the array. returns 1342
const arr = ["13,d42", "d44f2", "1g5", "1c42"];
console.log(arr.map(a => +a.match(/\d+/g).join('')).reduce((a, b) => a + b, 0)); // 1941 => the sum of [ 1342, 442, 15, 142 ]
// Fn to remove numeric part from input string
const stripNonNumeric=(str)=>{return str.replace(/\D/g,'');}
let input = ["13,d42", "d44f2", "1g5", "1c42"];
// Convert array to numeric array
let numericArray=input.map(item=>(Number(stripNonNumeric(item))))
// Sum array elements
const sum = numericArray.reduce((partialSum, a) => partialSum + a, 0);
console.log(sum);
Related
i have an array ["academy"] and i need count chars from the string in the array.
output:
a:2
c:1
d:1
e:1
m:1
y:1
like this
i tried two for loops
function sumChar(arr){
let alph="abcdefghijklmnopqrstuvxyz";
let count=0;
for (const iterator of arr) {
for(let i=0; i<alph.length; i++){
if(iterator.charAt(i)==alph[i]){
count++;
console.log(`${iterator[i]} : ${count}`);
count=0;
}
}
}
}
console.log(sumChar(["abdulloh"]));
it works wrong
Output:
a : 1
b : 1
h : 1
undefined
Here's a concise method. [...new Set(word.split(''))] creates an array of letters omitting any duplicates. .map takes each letter from that array and runs it through the length checker. ({ [m]: word.split(m).length - 1 }) sets the letter as the object key and the word.split(m).length - 1is a quick way to determine how many times that letter shows up.
const countLetters = word => (
[...new Set(word.split(''))].map(m => ({
[m]: word.split(m).length - 1
})))
console.log(countLetters("academy"))
You can check the occurrences using regex also. in this i made a method which checks for the character in the string. Hope it helps.
word: string = 'abcdefghijklkmnopqrstuvwxyzgg';
charsArrayWithCount = {};
CheckWordCount(): void {
for(var i = 0;i < this.word.length; i++){
if(this.charsArrayWithCount[this.word[i]] === undefined){
this.charsArrayWithCount[this.word[i]] = this.charCount(this.word, this.word[i]);
}
}
console.log(this.charsArrayWithCount);
}
charCount(string, char) {
let expression = new RegExp(char, "g");
return string.match(expression).length;
}
You can simply achieve this requirement with the help of Array.reduce() method.
Live Demo :
const arr = ["academy"];
const res = arr.map(word => {
return word.split('').reduce((obj, cur) => {
obj[cur] = obj[cur] ? obj[cur] + 1 : 1
return obj;
}, {});
});
console.log(res);
I think this is the simplest:
const input = 'academy';
const res = {};
input.split('').forEach(a => res[a] = (res[a] ?? 0) + 1);
console.log(res);
I have a array of string.
let arr=["robin","rohit","roy"];
Need to find all the common character present in all the strings in array.
Output Eg: r,o
I have tried to create a function for above case with multiple loops but i want to know what should be the efficient way to achive it.
Here's a functional solution which will work with an array of any iterable value (not just strings), and uses object identity comparison for value equality:
function findCommon (iterA, iterB) {
const common = new Set();
const uniqueB = new Set(iterB);
for (const value of iterA) if (uniqueB.has(value)) common.add(value);
return common;
}
function findAllCommon (arrayOfIter) {
if (arrayOfIter.length === 0) return [];
let common = new Set(arrayOfIter[0]);
for (let i = 1; i < arrayOfIter.length; i += 1) {
common = findCommon(common, arrayOfIter[i]);
}
return [...common];
}
const arr = ['robin', 'rohit', 'roy'];
const result = findAllCommon(arr);
console.log(result);
const arr = ["roooooobin","rohit","roy"];
const commonChars = (arr) => {
const charsCount = arr.reduce((sum, word) => {
const wordChars = word.split('').reduce((ws, c) => {
ws[c] = 1;
return ws;
}, {});
Object.keys(wordChars).forEach((c) => {
sum[c] = (sum[c] || 0) + 1;
});
return sum;
}, {});
return Object.keys(charsCount).filter(key => charsCount[key] === arr.length);
}
console.log(commonChars(arr));
Okay, the idea is to count the amount of times each letter occurs but only counting 1 letter per string
let arr=["robin","rohit","roy"];
function commonLetter(array){
var count={} //object used for counting letters total
for(let i=0;i<array.length;i++){
//looping through the array
const cache={} //same letters only counted once here
for(let j=0;j<array[i].length;j++){
//looping through the string
let letter=array[i][j]
if(cache[letter]!==true){
//if letter not yet counted in this string
cache[letter]=true //well now it is counted in this string
count[letter]=(count[letter]||0)+1
//I don't say count[letter]++ because count[letter] may not be defined yet, hence (count[letter]||0)
}
}
}
return Object.keys(count)
.filter(letter=>count[letter]===array.length)
.join(',')
}
//usage
console.log(commonLetter(arr))
No matter which way you choose, you will still need to count all characters, you cannot get around O(n*2) as far as I know.
arr=["robin","rohit","roy"];
let commonChars = sumCommonCharacters(arr);
function sumCommonCharacters(arr) {
data = {};
for(let i = 0; i < arr.length; i++) {
for(let char in arr[i]) {
let key = arr[i][char];
data[key] = (data[key] != null) ? data[key]+1 : 1;
}
}
return data;
}
console.log(commonChars);
Here is a 1 liner if anyone interested
new Set(arr.map(d => [...d]).flat(Infinity).reduce((ac,d) => {(new RegExp(`(?:.*${d}.*){${arr.length}}`)).test(arr) && ac.push(d); return ac},[])) //{r,o}
You can use an object to check for the occurrences of each character. loop on the words in the array, then loop on the chars of each word.
let arr = ["robin","rohit","roy"];
const restWords = arr.slice(1);
const result = arr[0].split('').filter(char =>
restWords.every(word => word.includes(char)))
const uniqueChars = Array.from(new Set(result));
console.log(uniqueChars);
I have array of object with few words I want to know occurance of each word and push into key value pair format
let words = ["aabbbc", "dddeeef", "gghhhii"]
Output
[{a:2, b:3,c:1}, {d:3,e:3,f:1}, {g:2,h:3:i:2}]
This is a classic map and reduce task where one maps the array of strings and for each string creates the character-specific counter-statistics while reducing the string's character-sequence (...split('').reduce( ... )) and by programmatically building an object which counts/totals each character's occurrence.
console.log(
["aabbbc", "dddeeef", "gghhhii"]
.map(string =>
string
.split('')
.reduce((result, char) => {
result[char] = (result[char] ?? 0) + 1;
return result;
}, {})
)
)
// [{a:2, b:3,c:1}, {d:3,e:3,f:1}, {g:2,h:3:i:2}]
.as-console-wrapper { min-height: 100%!important; top: 0; }
let words = ["aabbbc", "dddeeef", "gghhhii"]
const occurences = (w) => {
const obj = {};
for (const c of w) {
if (obj[c] === undefined) obj[c] = 0;
obj[c]++;
}
return obj;
}
const arr = words.map(w => occurences(w));
console.log(arr)
Trying to keep it easy and readable:
const words = ['aabbbc', 'dddeeef', 'gghhhii']
const output = []
for (const word of words) {
const result = {}
for (const letter of word) {
result[letter] = result[letter] || 0
result[letter]++
}
output.push(result)
}
console.log({ output })
let words = ["aabbbc", "ddeeef", "ghhhii"]
let newArr = []
words.forEach((e,index)=>{
e.split('').forEach(n=>{
if(!newArr[index]){
newArr[index]={}
}
if(!newArr[index][n]){
newArr[index][n]=0
}
(newArr[index][n]>=0) && ++newArr[index][n]
})
})
console.log(newArr)
I would like to count all values where a letter appears first and return the letter with atleast half of all values in my object so for example I assuming I have an object like this
const sample = { "A,B,C": 4, "B,C,A": 3, "C,B,A": 2, "A,C,B": 2 };
I would return A because if you count all the values where A appears first you would get 6 (4+2)
This is what I currently have:
for (let votes of Object.values(sample)) {
sum += votes
}
stretchWin = Math.round(sum / 2)
winner = Object.entries(sample)
.filter(([, val]) => val >= stretchWin)
.map(([keys]) => keys)
With this I am getting an empty array because I am not counting all the values assigned to A
Iterate over the whole sample first to get a sum of the values by the first letter first, then iterate over that new object to identify which values match the target of half the total.
const sample = {
"A,B,C": 4,
"B,C,A": 3,
"C,B,A": 2,
"A,C,B": 2
};
const sumByChar = {};
for (const [key, value] of Object.entries(sample)) {
const char = key[0];
sumByChar[char] = (sumByChar[char] ?? 0) + value;
}
let sum = 0;
for (let votes of Object.values(sample)) {
sum += votes
}
const targetSum = Math.round(sum / 2);
const winners = Object.entries(sumByChar)
.filter(([, val]) => val >= targetSum)
.map(([key]) => key);
console.log(winners);
I'm not completely sure what you mean what the outcome should be. If I understand correctly you want something like this??
const sample = { "A,B,C": 4, "B,C,A": 3, "C,B,A": 2, "A,C,B": 2 };
const totalSum = Object.values(sample).reduce(
(previousValue, currentValue) => previousValue + currentValue,
0
);
const stretchWin = Math.round(totalSum / 2);
const winner = Object.entries(sample)
.filter(([key, value]) => {
const isFirstLetterA = key.startsWith("A");
return isFirstLetterA || value >= stretchWin;
})
.map(([key, value]) => value)
.reduce((previousValue, currentValue) => previousValue + currentValue, 0);
console.log(winner);
Need help inside the for loop to flip each character with the character before it.
function flip(str) {
//split string
//iterate through split string
//return joined string
var splitt = str.split('');
for(var i = 0; i < splitt.length; i++){
//flip every character with one before it
}
}
var output = flip('otatl');
console.log(output); // -> 'total'
function split(str) {
let splitt = str.split('');
for (let i=0; i<splitt.length-1; i+=2) {
const temp = splitt[i];
splitt[i] = splitt[i+1];
splitt[i+1] = temp;
}
return splitt.join('');
}
You can use ES6 destructuring assignment.
function flip(str) {
//split string
//iterate through split string
//return joined string
let splitt = str.split('');
for (let i=0; i < splitt.length; i++){
//flip every character with one before it
if (i%2 == 1) {
[splitt[i-1], splitt[i]] = [splitt[i], splitt[i-1]];
}
}
return splitt.join('');
}
let output = flip('otatl');
console.log(output); // -> 'total'
You can combine this technique with gillyb's loop pattern to reduce the iterations as follows:
function flip(str) {
//split string
//iterate through split string
//return joined string
let splitt = str.split('');
for (let i=1; i < splitt.length; i+=2){
//flip every character with one before it
[splitt[i-1], splitt[i]] = [splitt[i], splitt[i-1]];
}
return splitt.join('');
}
let output = flip('otatl');
console.log(output); // -> 'total'
Can do something similar with regex and array manipulation
const flip = (stringToFlip) => stringToFlip
.split(/(.{2})/) // array of strings of 2 chars
.map((e) => e.split('') // convert each string piece to array
.reverse() // reverse array
.join('') // convert array piece back to string
)
.join(''); // combine all parts
const result = flip('otatl');
console.log("flip('otatl')");
console.log(result);
If we're not restricted to for loops, this is my (slightly too code golf-ish?) answer:
const flip = (str) =>
str
.split('')
.reduce((a, v, i) => (a[i + ((i % 2) * -2 + 1)] = v, a), [])
.join('');
console.log(flip('otatl'));
console.log(flip('lfpi'));
I'm sorry I am late to the party but you can use reduce().
let input = "vanjskojfdghpja";
let output = input
.split('')
.reduce(([o,p],c,i) => i%2?[o+c+p,'']:[o,c],['',''])
.join('');
console.log(output);
.as-console-wrapper { top: 0; max-height: 100% !important; }