Accessing indexes of a string inside an array and taking the sum - javascript

Ok so I am trying to access each individual number in the strings inside of this array.
var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'];
var str = "";
for (i=0; i<array.length; i++) {
str = array[i];
}
The problem is that this is the output: '999-992-1313'
and not the first element array[0]: '818-625-9945'
When I try doing a nested for loop to go through each element inside the string I am having trouble stating those elements.
var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'];
for (i=0; i<array.length; i++) {
for (j=0; j<array[i].length; j++) {
console.log(array[i][j]);
}
}
I do not know how to access each individual number inside of the string array[i]. I would like to find a way to make a counter such that if I encounter the number '8' I add 8 to the total score, so I can take the sum of each individual string element and see which number has the highest sum.
var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'];
for (i=0; i<array.length; i++) {
for (j=0; j<array[i].length; j++) {
if (array[i](j).indexOf('8') !== -1) {
// add one to total score
// then find a way to increase the index to the next index (might need help here also please)
}
}
}

Mabe this works for you. It utilized Array.prototype.reduce(), Array.prototype.map() and String.prototype.split().
This proposal literates through the given array and splits every string and then filter the gotten array with a check for '8'. The returned array is taken as count and added to the return value from the former iteration of reduce - and returned.
var array = ['818-625-9945', '999-992-1313', '888-222-2222', '999-123-1245'],
score = array.reduce(function (r, a) {
return r + a.split('').filter(function (b) { return b === '8'; }).length;
}, 0);
document.write('Score: ' + score);
A suggested approach with counting all '8' on every string:
var array = ['818-625-9945', '999-992-1313', '888-222-2222', '999-123-1245'],
score = array.map(function (a) {
return a.split('').filter(function (b) { return b === '8'; }).length;
});
document.write('Score: ' + score);

Actually rereading your question gave me a better idea of what you want. You simply want to count and retrieve the number of 8's per string and which index in your array conforms with this maximum 8 value. This function retrieves the index where the value was found in the array, how many times 8 was found and what is the string value for this result. (or returns an empty object in case you give in an empty array)
This you could easily do with:
'use strict';
var array = ['818-625-9945', '999-992-1313', '888-222-2222', '999-123-1245'];
function getHighestEightCountFromArray(arr) {
var max = 0,
result = {};
if (arr && arr.forEach) {
arr.forEach(function(value, idx) {
var cnt = value.split('8').length;
if (max < cnt) {
// found more nr 8 in this section (nl: cnt - 1)
max = cnt;
// store the value that gave this max
result = {
count: cnt - 1,
value: value,
index: idx
};
}
});
}
return result;
}
console.log(getHighestEightCountFromArray(array));
The only thing here is that when an equal amount of counts is found, it will still use the first one found, here you could decide which "maximum"
should be preferred(first one in the array, or the newest / latest one in the array)
OLD
I'm not sure which sums you are missing, but you could do it in the following way.
There I first loop over all the items in the array, then I use the String.prototype.split function to split the single array items into an array which would then contain ['818', '625', '9945']. Then for each value you can repeat the same style, nl: Split the value you are receiving and then loop over all single values. Those then get convert to a number by using Number.parseInt an then all the values are counted together.
There are definitelly shorter ways, but this is a way how you could do it
'use strict';
var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'],
sumPerIndex = [],
totalSum = 0;
array.forEach(function(item, idx) {
var values = item.split('-'), subArray = [], itemSum = 0;
values.forEach(function(value) {
var singleItems = value.split(''),
charSum = 0;
singleItems.forEach(function(char) {
charSum += parseInt(char);
});
itemSum += charSum;
subArray.push(charSum);
console.log('Sum for chars of ' + value + ' = ' + charSum);
});
sumPerIndex.push(subArray);
totalSum += itemSum;
console.log('Sum for single values of ' + item + ' = ' + itemSum);
});
console.log('Total sum of all elements: ' + totalSum);
console.log('All invidual sums', sumPerIndex);

Related

I need to create a function in javascript to show how many members of array are less than a given number

I think that my error is in the return section
I've tried many things but I can't find the solution
the question is : "Write a function called countNums that gets two arguments - an array of numbers and some member
And prints to the screen some organs in an array that are smaller than the given organ.
For the screen, countNums([7,3,9,1,20], 10) will be printed to read: for example
"4 elements are less than 10."
function countNums(arr, element) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] < element) {
return " " + arr[i] + "elements are less than" + element + " ";
}
}
}
arr = [14, 25, 36, 50]
document.write(countNums(arr, 20));
Javascript has functions that can help you do this easily, such as array.filter which will return a subset of an array depending upon the condition.
However, I've presented an answer that uses the logic you outlined in your own attempt but modified in order to return the correct result.
The primary problem with your code was that you were not actually counting the number of elements below the target number - instead you returned when the first array element was below the target number.
I've fixed that by adding a count variable to keep a running count.
In the if statement, if the array element is lower than the number then count is incremented by one. At the end of the function, the total running count is returned.
Here's a working snippet showing this:
function countNums(arr, element)
{
let count = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] < element)
count++;
}
return count;
}
let arr = [14,25,36,50]
let num = 20;
let result = countNums(arr, num);
document.write(result + " element(s) are less than " + num);
In the snippet above, you can modify num to specify the target number that the array elements must be lower than. The output statement will be modified automatically to show the correct wording.
It's a typical situation to use Array built-in method "reduce":
const array = [12, 6, 11, 4]
const count = (arr, num) => {
return `${arr.reduce(
(acc, val) => val < num
? acc + 1
: acc, 0
)} number(s) are less than ${num}`
}
console.log(count(array, 10))

Finding a first letter most repeated in an string

Good evening, I proceed to explain my situation. I started to get interested in javascript which started to dabble
in this language, I have been doing some online courses which I have encountered the following task, basically I am trying through the condition "for" tell me what is the first repeated letter of a string also adding the funsion ".UpperCase () "which at the beginning worked best, until I entered more characters to the string in this case" x "throwing me as output result" undefined "instead of" the most repeated word is: X "reach the case that the string should Consider all the letters regardless of whether they are lowercase or capital letters, for which I ask for help to understand if ¿there is another way? for this task and thus move forward (Sorry for my bad english)
Well i making this task in JavasScript with Atom Editor
var word = "SQSQSQSSaaaassssxxxY";
var contendor = [];
var calc = [];
var mycalc = 0;
function repeat() {
for (var i = 0; i < word.length; i++) {
if (contendor.includes(word[i])) {} else {
contendor.push(word[i])
calc.push(0)
}
}
for (var p = 0; p < word.length; p++) {
for (var l = 0; l < contendor.length; l++) {
if (word[p].toUpperCase() == word[l]) {
calc[l] = calc[l] + 1
}
}
}
for (var f = 0; f < calc.length; f++) {
if (calc[f] > mycalc) {
mycalc = calc[f]
}
}
}
repeat()
console.log("The first letter repeated its: " + contendor[mycalc])
I expected the output of the String to be: "X"
but the actual output is: "Undefined"
The first error in your script is that you store the wrong value in mycalc:
mycalc = calc[f]
Since you want mycalc to be an index, the above should have been
mycalc = f
Now, you will get a result, but your code is actually going through a lot of effort to find the uppercase character that is repeated most often, not first.
Your comparison should have used toUpperCase on both sides of the comparison, otherwise lower case letters will never match.
To get the character that was repeated most often, you could use a Map (to keep track of the counts like you did in calc):
function mostRepeated(str) {
const map = new Map;
let result;
let maxCount = 0;
for (let ch of str) {
ch = ch.toUpperCase();
let count = (map.get(ch) || 0) + 1;
map.set(ch, count);
if (count > maxCount) {
maxCount = count;
result = ch;
}
}
return result;
}
var word = "MBXAYMZAXmZYxxxxxxxxxxmBxAYMZaXmZY";
console.log(mostRepeated(word));
Note that you should better use function parameters and local variables. Declaring your variables as global is not considered best practice.
You could find the letter that occurs the most number of times in a string by:
first creating a map that relates each unique letter, to the number of times it occurs in the string
converting that map to an array of "key/value" entries, and then sorting those entries by the "count value"
returning the "letter key" that has the largest count
One way to express this in JavaScript would be via the following:
function findMaxLetter(word) {
/* Create a map that relates letters to the number of times that letter occours */
const letterCounts = Array.from(word).reduce((map, letter) => {
return { ...map, [letter] : (map[letter] === undefined ? 0 : map[letter] + 1) }
}, {})
/* Sort letters by the number of times they occour, as determined in letterCounts map */
const letters = Object.entries(letterCounts).sort(([letter0, count0], [letter1, count1]) => {
return count1 - count0
})
.map(([letter]) => letter)
/* Return letter that occoured the most number of times */
return letters[0]
}
console.log("The first letter repeated its: " + findMaxLetter("MBXAYMZAXmZYxxxxxxxxxxmBxAYMZaXmZY"))
I this is solution is most detailed for you
function func( word ){
word = word.toLowerCase();
var i, charCountCache = {};
//store all char counts into an object
for( i = 0; i < word.length; i++){
if( charCountCache[ word[ i ] ] )
charCountCache[ word[ i ] ] = charCountCache[ word[ i ] ] + 1;
else
charCountCache[ word[ i ] ] = 1;
}
//find the max value of char count in cached object
var fieldNames = Object.keys( charCountCache )
, fieldValues = Object.values( charCountCache )
, mostReapeatChar = '', mostReapeatCharCount = 0;
for( i = 0; i < fieldNames.length; i++ ){
if( mostReapeatCharCount < fieldValues[i] ){
mostReapeatCharCount = fieldValues[i];
mostReapeatChar = fieldNames[i];
}
}
console.log('most repeating char: ', mostReapeatChar, ' no of times: ', mostReapeatCharCount )
}
console.log("The first letter repeated its: " + contendor[mycalc])
You tried to print the 14th index of contendor which has only 9 values, that is why your log result was undefined.
You probably wanted to print word[mycalc].
Also if you intended to count x as X, you should have added toUpperCase() to every letter you process/go-through.
This is only a note to the issues in your code, there are better/faster/cleaner solutions to reach the result which i am sure other answers will provide.
my advice would be to create a hashmap such as
letter => [indexLetter1, indexLetter2].
From that hashmap, you could easily find your first repeated letters.
For that string MBXAYMZAXmZYxxxxxxxxxxmBxAYMZaXmZY, hashmap will look like
[
M => [0,5,..],
B => [1, ..],
X => [2, ..],
...
]
now you can find every letter with multiple values in its array, then in those arrays take the one with the lowest value.
If you want to get the index of most repeated letter, you can use Array.from to convert the word into an array. Add a map function to make all letters uppercase.
Get the count of each letter by using reduce and Object.entries
Use indexOf to the get the index of the lettet in the array. Please note that indexOf count the letters from 0.
var word = "MBXAYMZAXmZYxxxxxxxxxxmBxAYMZaXmZY";
var letters = Array.from(word, o => o.toUpperCase());
var [highestLetter, highestCount]= Object.entries(letters.reduce((c, v) => (c[v] = (c[v] || 0) + 1, c), {})).reduce((c, v) => c[1] > v[1] ? c : v);
var index = letters.indexOf(highestLetter);
console.log("Most repeated letter:", highestLetter);
console.log("Count:", highestCount);
console.log("First Index:", index);

How do I convert strings in an array to numbers using forEach?

I am trying to sum the contents of an array like these:
var cardsBen = [10,2]
var cardsAmy = [4,10]
When I use a for loop, it works.
for(var i = 0; i < cardsBen.length; i++){
cardsBen[i] = Number(cardsBen[i]);
}
When I use forEach, it doesn't convert.
cardsAmy.forEach(function(item)
{
Number(item);
});
I know this because, when I then reduce the arrays, I get 12 for Ben and 410 for Amy.
var sumBen = cardsBen.reduce(function(sum, nbr){return sum + nbr});
var sumAmy = cardsAmy.reduce(function(sum, nbr){return sum + nbr});
Primitive values can't be mutated. So when doing Number(item) you have to assign that back to the array like:
cardsAmy.forEach(function(item, i) {
cardsAmy[i] = Number(item);
});
And you can do that directly in reduce (without needing the above forEach code) like:
var sumBen = cardsBen.reduce(function(sum, nbr) { return sum + Number(nbr); }, 0);
// ^^^^^^^ ^
You could use reduce with an implicit casting to number with an unary plus +.
sum = array.reduce(function (s, v) {
return s + +v;
}, 0);

How can i ignore duplicate values in if statement?

var availableMarketGroups = {};
angular.forEach(function (market) {
if (availableMarketGroups[market.group_id]) { // market.group_id is not sorted id
availableMarketGroups[market.group_id].count++;
}
});
market.group_id - number ,not sorted, and sometimes its duplicates
availableMarketGroups[market.group_id].count - its length
Lets see the image for more info.
The numbers of the market groups don't represent real amount of markets.
availableMarketGroups[market.group_id].count show - 15 ,but in real it should be 5 (5 groups) ,because market.group_id is duplicates.
How can i ignore duplicated market.group_id values in if statement ?
var availableMarketGroups = {};
var groupsProcessed = [];
angular.forEach(availableMarketGroups, function(marketGroup) {
if (groupsProcessed.indexOf(marketGroup.group_id) < 0) {
groupsProcessed.push(marketGroup.group_id);
availableMarketGroups[market.group_id].count++;
}
});
Answer for counting unique array elements is to make a function as given below.
var counts = {};
for (var i = 0; i < arr.length; i++) {
counts[arr[i]] = 1 + (counts[arr[i]] || 0);
}
It will return the unique counts of elements in the array.
Reference : Count unique elements in array without sorting
Hard to say without your data. Generally speaking, you should be able to reduce this down to the unique Set of group_ids:
const uniqueGroups = markets.reduce(function(set, market) {
if (!set.has(market.group_id)) {
set.add(market.group_id);
}
return set;
}, new Set());
console.log('Unique group count: ', uniqueGroups.size);
You can use underscore:
var newObj = _.uniq(market, function(p){ return p.group_id; });

javascript: limit number of items

sorry but I'm new in javascrit.
I'm writing a simple rss reader, but I want to limit the number of feeds to 5 items, because the my target site can have 100 or more.
Here the code:
$("#mainPage").live("pageinit", function () {
$("h1", this).text(title);
$.get(RSS, {}, function (res, code) {
var xml = $(res);
var items = xml.find("item");
var items = $items.length && i < 5; i++); // here the problem!!
var entry = "";
$.each(items, function (i, v) {
entry = {
title:$(v).find("title").text(),
link:$(v).find("link").text(),
description:$.trim($(v).find("encoded").text()),
category:$.trim($(v).find("category").text()),
date:$(v).find("pubDate").text().substr(0,16),
autor:$(v).find("creator").text()
};
entries.push(entry);
});
var s = '';
$.each(entries, function(i, v) {
s += '<li>' + v.title + '<br><i>' + v.autor + ' - ' + v.date + '</i></li>';
});
$("#linksList").append(s);
$("#linksList").listview("refresh");
});
});
The problem is that when I try to limit the number of items adding
var items = $items.length && i < 5; i++);
the javascript stop to works. :-(
How to do it?
var items = $items.length && i < 5; i++); is invalid I think you want to
var items = items.slice(0, 4); is what you want.
https://api.jquery.com/slice/ (as pointed out to me, it's a jQuery object)
The jQuery object itself behaves much like an array; it has a length
property and the elements in the object can be accessed by their
numeric indices [0] to [length-1]. Note that a jQuery object is not
actually a Javascript Array object, so it does not have all the
methods of a true Array object such as join().
Because Javascript is 0-based (starts to count from 0) you want element 0 to 4, in order to get the first 5 elements.
You can use lt(n) function
var items = xml.find("item:lt(5)");

Categories