How can I count the array depending on the value..
I have an array with this value..
var myArr = new Array(3);
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b";
I need to count the array depending on the value
Array with Value A is 2
Array with value B is 1
Thanks!
var myArr = new Array(3);
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b";
function count(array, value) {
var counter = 0;
for(var i=0;i<array.length;i++) {
if (array[i] === value) counter++;
}
return counter;
}
var result = count(myArr, "a");
alert(result);
If you're interested in a built-in function... you could always add your own.
Array.prototype.count = function(value) {
var counter = 0;
for(var i=0;i<this.length;i++) {
if (this[i] === value) counter++;
}
return counter;
};
Then you could use it like this.
var result = myArr.count("a");
alert(result);
Oh well, beaten to the punch, but here's my version.
var myArr = new Array(3);
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b"
getCountFromVal( 'a', myArr );
function getCountFromVal( val, arr )
{
var total = arr.length;
var matches = 0;
for( var i = 0; i < total; i++ )
{
if( arr[i] === val )
{
matches++;
}
}
console.log(matches);
return matches;
}
Live Demo: http://jsfiddle.net/CLjyj/1/
var myArr = new Array(3);
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b";
function getNum(aVal)
{
num=0;
for(i=0;i<myArr.length;i++)
{
if(myArr[i]==aVal)
num++;
}
return num;
}
alert(getNum('a')); //here is the use
I would use Array.filter
var arr = ['a', 'b', 'b']
arr.filter(val => val === 'b').length // 2
Everyone's already given the obvious function, so I'm going to try and make another solution:
var myArr = [];
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b";
function count(arr, value){
var tempArr = arr.join('').split(''), //Creates a copy instead of a reference
matches = 0,
foundIndex = tempArr.indexOf(value); //Find the index of the value's first occurence
while(foundIndex !== -1){
tempArr.splice(foundIndex, 1); //Remove that value so you can find the next
foundIndex = tempArr.indexOf(value);
matches++;
}
return matches;
}
//Call it this way
document.write(count(myArr, 'b'));
Demo
You can use Lodash's countBy function:
_.countBy(myArr);
Example:
var myArr = new Array(3);
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b";
const result = _.countBy(myArr);
// Get the count of `a` value
console.log('a', result.a);
// Get the count of `b` value
console.log('b', result.b);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
countBy Documentation
Related
Here is the problem:
Given two strings, find the number of common characters between them.
For s1 = "aabcc" and s2 = "adcaa", the output should be 3.
I have written this code :
function commonCharacterCount(s1, s2) {
var count = 0;
var str = "";
for (var i = 0; i < s1.length; i++) {
if (s2.indexOf(s1[i]) > -1 && str.indexOf(s1[i]) == -1) {
count++;
str.concat(s1[i])
}
}
return count;
}
console.log(commonCharacterCount("aabcc", "adcaa"));
It doesn't give the right answer, I wanna know where I am wrong?
There are other more efficient answers, but this answer is easier to understand. This loops through the first string, and checks if the second string contains that value. If it does, count increases and that element from s2 is removed to prevent duplicates.
function commonCharacterCount(s1, s2) {
var count = 0;
s1 = Array.from(s1);
s2 = Array.from(s2);
s1.forEach(e => {
if (s2.includes(e)) {
count++;
s2.splice(s2.indexOf(e), 1);
}
});
return count;
}
console.log(commonCharacterCount("aabcc", "adcaa"));
You can do that in following steps:
Create a function that return an object. With keys as letters and count as values
Get that count object of your both strings in the main function
Iterate through any of the object using for..in
Check other object have the key of first object.
If it have add the least one to count using Math.min()
let s1 = "aabcc"
let s2 = "adcaa"
function countChars(arr){
let obj = {};
arr.forEach(i => obj[i] ? obj[i]++ : obj[i] = 1);
return obj;
}
function common([...s1],[...s2]){
s1 = countChars(s1);
s2 = countChars(s2);
let count = 0;
for(let key in s1){
if(s2[key]) count += Math.min(s1[key],s2[key]);
}
return count
}
console.log(common(s1,s2))
After posting the question, i found that i havent looked the example well. i thought it wants unique common characters ..
and i changed it and now its right
function commonCharacterCount(s1, s2) {
var count = 0;
var str="";
for(var i=0; i<s1.length ; i++){
if(s2.indexOf(s1[i])>-1){
count++;
s2=s2.replace(s1[i],'');
}
}
return count;
}
Create 2 objects containing characters and their count for strings s1
and s2
Count the common keys in 2 objects and return count - Sum the common keys with minimum count in two strings
O(n) - time and O(n) - space complexities
function commonCharacterCount(s1, s2) {
let obj1 = {}
let obj2 = {}
for(let char of s1){
if(!obj1[char]) {
obj1[char] = 1
} else
obj1[char]++
}
for(let char of s2){
if(!obj2[char]) {
obj2[char] = 1
} else
obj2[char]++
}
console.log(obj1,obj2)
let count = 0
for(let key in obj1 ){
if(obj2[key])
count += Math.min(obj1[key],obj2[key])
}
return count
}
I think it would be a easier way to understand. :)
function commonCharacterCount(s1: string, s2: string): number {
let vs1 = [];
let vs2 = [];
let counter = 0;
vs1 = Array.from(s1);
vs2 = Array.from(s2);
vs1.sort();
vs2.sort();
let match_char = [];
for(let i = 0; i < vs1.length; i++){
for(let j = 0; j < vs2.length; j++){
if(vs1[i] == vs2[j]){
match_char.push(vs1[i]);
vs2.splice(j, 1);
break;
}
}
}
return match_char.length;
}
JavaScript ES6 clean solution. Use for...of loop and includes method.
var commonCharacterCount = (s1, s2) => {
const result = [];
const reference = [...s1];
let str = s2;
for (const letter of reference) {
if (str.includes(letter)) {
result.push(letter);
str = str.replace(letter, '');
}
}
// ['a', 'a', 'c'];
return result.length;
};
// Test:
console.log(commonCharacterCount('aabcc', 'adcaa'));
console.log(commonCharacterCount('abcd', 'aad'));
console.log(commonCharacterCount('geeksforgeeks', 'platformforgeeks'));
Cause .concat does not mutate the string called on, but it returns a new one, do:
str = str.concat(s1[i]);
or just
str += s1[i];
You can store the frequencies of each of the characters and go over this map (char->frequency) and find the common ones.
function common(a, b) {
const m1 = {};
const m2 = {};
let count = 0;
for (const c of a) m1[c] = m1[c] ? m1[c]+1 : 1;
for (const c of b) m2[c] = m2[c] ? m2[c]+1 : 1;
for (const c of Object.keys(m1)) if (m2[c]) count += Math.min(m1[c], m2[c]);
return count;
}
Need to replace a value "y" with "#" in an array and also need to count the "y" value in an array.
x = ['a','b','c'];
z = ['z','y','y'];
var a = x.concat(z);
var b = a.sort();
var count = 0;
for(var i = 0; i < b.length; i++){
if(b[i] == "y") {
b['y'] == "#";
var c = count++;
}
}
console.log(b);
console.log(c+1);
Fiddle
declare all variables
assign the right value, do not make a comparison b[i] = "#";,
use count variable, and not c
no need to use b, because sort sorts the given array.
var x = ['a', 'b', 'c'];
var z = ['z', 'y', 'y'];
var a = x.concat(z);
var count = 0;
a.sort();
for (var i = 0; i < a.length; i++){
if (a[i] == "y") {
a[i] = "#";
count++;
}
}
console.log(a);
console.log(count);
You can use reduce with destructuring assignment to effectively return 2 values
var x = ['a','b','c']
var z = ['z','y','y']
var a = x.concat(z)
var [count, b] = a.reduce(([count,b],x)=> {
if (x === 'y')
return [count + 1, [...b, '#']]
else
return [count, [...b, x]]
}, [0, []])
console.log(count) // 2
console.log(b) // ['a', 'b', 'c', 'z', '#', '#']
If you really want the array sorted before replacing 'y' and getting the count, you should know that Array.prototype.sort will mutate the original array. Also, assignment of an array to a variable is by reference.
So when you write this...
var b = a.sort();
You should know that a will be sorted, and b is just a second reference to the exact same array. b is not a separate copy.
If you'd like to make a separate copy, you can do this
// make B a sorted copy of A. do not modify A.
var b = a.slice(0).sort();
== is comparison operator
= is assignment operator
Change to this :
for(var i = 0; i < b.length; i++){
if(b[i] == "y") {
b[i] = "#";
var c = count++;
}
}
from
for(var i = 0; i < b.length; i++){
if(b[i] == "y") {
b['y'] == "#";
count++;
}
}
x = ['a', 'b', 'c'];
z = ['z', 'y', 'y'];
var a = x.concat(z);
var b = a.sort();
var count = 0;
for (var i = 0; i < b.length; i++) {
if (b[i] == "y") {
b[i] = "#";
count++;
}
}
console.log(b);
console.log(count);
You can also use Array#map.
var x = ['a','b','c'];
var z = ['z','y','y'];
var a = x.concat(z);
var b = a.sort();
var count = 0;
b = b.map(function(v) {
if(v == 'y') {
count++;
return '#';
} else {
return v;
}
});
console.log(b);
console.log(count);
I'm not sure, but is this what you want?
x = ['a','b','c'];
z = ['z','y','y'];
var a = x.concat(z);
var b = a.sort();
var count = 0;
for(var i = 0; i < b.length; i++){
if(b[i] == "y") {
b[i] = "#";
var c = count++;
}
}
console.log(b);
console.log(c+1);
jsfiddle
If you are the fan of less line of code, then this one line (or maybe two line) implementation would be noticeable. ;)
BUT the main reason of my answer was about the sort return value.
as mentioned in documentation:
The sort() method sorts the elements of an array in place and returns
the array. The sort is not necessarily stable. The default sort order
is according to string Unicode code points.
So the sort() method do the action in place and returns the result (the array) too.
var x = ['a', 'b', 'c'],
z = ['z', 'y', 'y'],
toReplace = 'y',
replaceWith = '#',
count = 0;
var result = x.concat(z).sort()
.map((v, i, a) => v === toReplace ? ++count && replaceWith : v);
console.log(result, count);
So let's say I have a two arrays which consists of numbers.
var arr1 = [1,2,3,4,5];
var arr2 = [1,1,1,4,4,5,5,2];
Is it possible to compare this two arrays in order to get most repeated number in two of them (for this example this number would be "1")?
There could be any numbers of any value in arrays.
Try this
function maxAppearedNos()
{
var arr1 = [1,2,3,4,5,2,2,2,2,2,2,2,2];
var arr2 = [1,1,1,4,4,5,5,2];
var concatenatedArray = arr1.concat(arr2);
var macCountNos = getMaxAppearedNos(concatenatedArray);
}
function getMaxAppearedNos(array)
{
if(array.length == 0)
return null;
var modeMap = {};
var maxEl = array[0], maxCount = 1;
for(var i = 0; i < array.length; i++)
{
var el = array[i];
if(modeMap[el] == null)
modeMap[el] = 1;
else
modeMap[el]++;
if(modeMap[el] > maxCount)
{
maxEl = el;
maxCount = modeMap[el];
}
}
return maxEl;
}
maxAppearedNos();
I have an array containing the individual letters of a word and i want to search the array to return the index values of certain letters. However, if the word contains more a letter more than once (such as 'tree') the programme only returns one index value.
This is a sample of the code:
var chosenWord = "tree";
var individualLetters = chosenWord.split('');
var isLetterThere = individualLetters.indexOf(e);
console.log(isLetterThere);
this code will return the number '2', as that is the first instance of the letter 'e'. How would i get it to return 2 and 3 in the integer format, so that i could use them to replace items in another array using the .splice function.
indexOf takes a second parameter, as the position where it should start searching from.
So my approach would be:
function findLetterPositions(text, letter) {
var positions = new Array(),
pos = -1;
while ((pos = text.indexOf(letter, pos + 1)) != -1) {
positions.push(pos);
}
return positions;
}
console.log(findLetterPositions("Some eerie eels in every ensemble.", "e"));
http://jsfiddle.net/h2s7hk1r/
You could write a function like this:
function indexesOf(myWord, myLetter)
{
var indexes = new Array();
for(var i = 0; i < myWord.length; i++)
{
if(myWord.charAt(i) == myLetter)
{
indexes.push(i);
}
}
return indexes;
}
console.log(indexesOf("tree", "e"));
Loop through it as here:
var chosenWord = "tree";
var specifiedLetter = "e";
var individualLetters = chosenWord.split('');
var matches = [];
for(i = 0;i<individualLetters.length;i++){
if(individualLetters[i] == specifiedLetter)
matches[matches.length] = i;
}
console.log(matches);
An alternative using string methods.
var str = "thisisasimpleinput";
var cpy = str;
var indexes = [];
var n = -1;
for (var i = cpy.indexOf('i'); i > -1; i = cpy.indexOf('i')) {
n += i;
n++;
indexes.push(n);
cpy = cpy.slice(++i);
}
alert(indexes.toString());
var getLetterIndexes = function(word, letter) {
var indexes = [];
word.split("").forEach(function(el, i) {
el === letter && indexes.push(i);
});
return indexes;
};
getLetterIndexes("tree", "e"); // [2, 3]
//Get message from textarea
var msg = $('#mytextarea').val();
//Convert string to array of letters
// eg. cata = ['c','a','t','a']
var msgLettersAsArray = msg.split('');
What I need to do now is replace the single letters,something like this
c = b;
a = e;
t = c;
a = e;
//array neeeds to be converted from this:
var array = ['c','a','t','a'];
// to this:
var array = ['b','e','c','e'];
Is there any way to achieve this?
All I need to do is replace the letters that are already in the array with letters of my choice
It's quite simple, just define a translation map and use Array.prototype.map.
var translationMap = {
c: 'b',
a: 'e',
t: 'c'
};
//returns ['b','e','c','e']
['c','a','t','a'].map(function (letter) { return translationMap[letter] || letter; });
EDIT: It seems you actually just wanted to replace letters in the string, in this case #phylax answer would be correct. There is no need to use arrays for a simple string replacement.
function replaceChars(str, map) {
var i, reg = "";
for (i in map)
reg += i;
return str.replace(
new RegExp("["+reg.replace(/(\]|-|\\)/,"\\$1")+"]",'g'),
function(char) { return map[char]; }
);
}
//Get message from textarea
var msg = $('#mytextarea').val(); // "cata"
replaceChars(msg, {c:'b', a:'e', t:'c', a:'e'}); // "bece"
Just making an answer out of my comment:
Like OP said, its ok to be done without the split(). And its possible to do with only one call to String.replace():
var map = {
c: 'b',
a: 'e',
t: 'c'
};
msg.replace(/[a-z0-9]/g, function (i) { return map[i] || i; })
The RegExp can possibly made event simpler:
msg.replace(/./g, function (i) { return map[i] || i; })
Sure, just use a for loop:
var array = ['c','a','t','a'];
for (var i = 0; i < array.length; i++)
{
var cur = array[i];
if (cur == 'c') {
array[i] = 'b';
} else if (cur == 'a') {
array[i] = 't';
} else if (cur == 't') {
array[i] = 'c';
}
}
But using an object to store these mappings can make your code even more compact:
var array = ['c','a','t','a'];
var transform = { 'c': 'b', 'a': 'e', 't': 'c' };
for (var i = 0; i < array.length; i++)
{
array[i] = transform[array[i]];
}
not tested but it should work
var replaxe = {
'c':'b',
'e':'d'
},
array = ['c','e'],
result = [];
for(var item in array){
result.push(replaxe[item]);
}
console.log(result);
RUN THIS IN YOUR FIRE BUG CONSOLE
var array = ['c','a','t','a'];
var myarray = [];
for(i=0; i<=array.length; i++)
{
if(array[i] == 'c' )
{
array[i] = 'b'
}
if(array[i] == 'a' )
{
array[i] = 'e'
}
if(array[i] == 't' )
{
array[i] = 'c'
}
if(array[i] == 'a' )
{
array[i] = 'a'
}
}
console.log(myarray);
I would recommend using a switch-case for every element in the array.
for (i in array) {
switch (array[i]) {
case "c":
array[i] = "b";
break;
case "a":
array[i] = "e";
break;
case "t":
array[i] = "c";
break;
}
}