how can i count chars from word which in the array? - javascript

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);

Related

I have a array of string have to find all the common character present from all strings

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);

Find occurance of characters in array of object using js

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)

How to flip every character with the character next to it. Javascript

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; }

Find the first unique value in an array or string

How can I get one unique value in an array or string? Only the first value. Pure JS only.
My example:
function searchValue () {
let inputText = [1,1,4,2,2,2,3,1];
let foundedValue;
for (let i = 0; i < inputText.length; i++) {
if (i === inputText.indexOf(inputText[i]) && i === inputText.lastIndexOf(inputText[i])) {
foundedValue = inputText[i];
break;
} else {
foundedValue = "not founded.";
}
}
return foundedValue;
}
console.log("Search value: "+ searchValue())
Answer is 4.
But, I need a short solution. Using the find() and filter() functions.
You can find the first unique item in your array using find() and comparing indexOf() to lastIndexOf() to determine whether or not there is more than one instance of an item in the array. If you need to find unique characters in a string, then you can first split it into an array and then use the same approach.
const arr = [1, 1, 4, 2, 2, 2, 3, 1];
const result = arr.find((x) => arr.indexOf(x) === arr.lastIndexOf(x));
console.log(result);
// 4
const text = 'aadbbbca';
const textarr = text.split('');
const textresult = textarr.find((x) => textarr.indexOf(x) === textarr.lastIndexOf(x));
console.log(textresult);
// d
You can try this.
const arr = [1, 1, 4, 2, 2, 2, 3, 1];
let r = {};
arr.map(a => r[a] = (r[a] || 0) +1)
var res = arr.find(a => r[a] === 1 )
console.log(res)
You can use js Set() object.
At first you could create a Set of duplicated elements.
const inputText = [1,1,4,2,2,2,3,1];
const duplicatesSet= inputText.reduce((dupSet, el) =>
inputText.filter(arrEl => arrEl === el).length > 1 ?
dupSet.add(el) : dupSet
, new Set());
Second you could use array.find. It returns first duplicated element.
const firstDupElement = inputText.find(el => duplicatesSet.has(el));
const searchValue = (_param) => {
for (let i= 0; i < _param.length; i+= 1) {
if (_param.indexOf(_param[i]) === _param.lastIndexOf(_param[i])) return _param[i];
}
return "not founded.";
}
let arr = [1,1,2,2,2,1,3,1,4,4,5]
const dupelearray = (array) => {
let arr2 =[...arr]
let ele = []
let state = false
arr2.map((i,index)=>{
arr2.splice(index,1)
arr.map((j)=>{
return arr2.includes(j) ? null : state=true
})
state && ele.push(i)
state=false
arr2.splice(index,0,i)
})
return console.log(arr.indexOf(ele[0]))
}
dupelearray(arr)
wow i didnt knew lastindexof method and was making this algo so difficult
btw this solution also works but definitely i am new in algo so this will take much more time but the solution still works!!!!!! damn should remember more methods or you have to think so much -_-

How to count words from window.prompt and sort them by number of apperance?

I need to count words from prompt and write them to the array. Next I have to count their appearance and sort them.
I have code like this:
let a = window.prompt("Write sentence")
a = a.split(" ")
console.log(a)
var i = 0;
for (let i = 0; i < a.length; i++) {
a[i].toUpperCase;
let res = a[i].replace(",", "").replace(".", "")
var count = {};
a.forEach(function(i) {
count[i] = (count[i] || 0) + 1;
});
console.log(count);
document.write(res + "<br>")
}
I don't know how to connect my word with specific number for number of appearances and write this words one time.
On the end it should look like:
a = "This sentence, this stentence, this sentence, nice."
This - 3
Sentence - 3
nice - 1
If I don't misunderstood your requirements then Array.prototype.reduce() and Array.prototype.sort() will the trick for you. Imagine I got the example string from your window.prompt()
let string = `this constructor doesn't have neither a toString nor a valueOf. Both toString and valueOf are missing`;
let array = string.split(' ');
//console.log(array);
let result = array.reduce((obj, word) => {
++obj[word] || (obj[word] = 1); // OR obj[word] = (++obj[word] || 1);
return obj;
}, {});
sorted_result = Object.keys(result).sort(function(a,b){return result[a]-result[b]})
console.log(result);
console.log(sorted_result);
AS PER QUESTION EDIT
let string = `This sentence, this sentence, this sentence, nice.`;
let array = string.split(' ');
array = array.map(v => v.toLowerCase().replace(/[.,\s]/g, ''))
let result = array.reduce((obj, word) => {
++obj[word] || (obj[word] = 1); // OR obj[word] = (++obj[word] || 1);
return obj;
}, {});
console.log(result)
You can use reduce. Like so:
const wordsArray = [...].map(w => w.toLowerCase());
const wordsOcurrenceObj = wordsAray.reduce((acc, word) => {
if (!acc[word]) {
acc[word] = 0;
}
acc[word] += 1;
return acc;
}, {});
What this does is keep track of the words in an object. When a word is not there, initializes with zero. And then adds a 1 every time you encounter that word. You will end up with an object like this:
{
'word': 3,
'other': 1,
...
}
Add another loop at the end that goes over the counts and prints them:
for(let word in count) {
console.log(word + " appeared " + count[word] + " times");
}

Categories