Javascript - Sum solution [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am getting below line in my source file and I would like to sum those values separated by pipe ("|")
There is no limit for the values coming in the line (might be 100 values)
10|20|30|40|[no limit for values] - Separator is pipe "|"
The ouptput would be 100
Please help to write a javascript function for the above query.
Regards
Jay

You should take a look at JavaScript's built-in functions: With split you can split your string into an array, with reduce you can 'reduce' your array to a single value, in that case via summation. These two links should provide you enough information for building your code.

You could try something like below:
function sum(value){
var total = 0;
var array = value.split(",").map(Number);
for( var i = 0; i < array.length; i++) {
total += array[i];
}
alert(total);
}
var value = "10|20|30|40".replace(/\|/g, ',');
console.log(sum(value));
https://jsfiddle.net/f7uqw7cL/

Related

Cast int array as byte array in Javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm trying to take an array of integers and cast it to bytes in JavaScript but can't quite figure out how to do it.
The input would look something like [2,-76,7,2,8,69,82,88,87,2,52,50,...].
If I was going to do it in another language like Java I'd use something like the following.
byte[] bytArr = new byte[intArray.size()];
for (int i = 0; i < intArray.size(); i++) {
bytArr[i] = (byte) intArray[i];
}
I'm pretty new to JS so not sure if this is even possible...
You can use Int8Array, which is a typed array.
const arr = Int8Array.from([2,-76,7,2,8,69,82,88,87,2,52,50]);

Integer comparison within score board app, score difference equal two [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm writting an score board app.
Got two integers, i need to compare them, for example
to know when game should be ended, eg. score = 20:22, 24:26 (score difference to end the game should be equal to two)
How i can make such comparison with js?
You can use split() method to separate scores into two different elements, and then afterwards just compare them.
function isGameOver(score, differenceToWin) {
var scoreArray = score.split(":");
return Math.abs(scoreArray[0] - scoreArray[1]) > differenceToWin;
}
isGameOver('24:26', 2)
EDIT: In case you only need to compare two integers, go ahead and use only the return statement line:
var score1 = 24;
var score2 = 26;
var differenceToWin = 2;
var isGameOver = Math.abs(score1 - score2) > differenceToWin;

How to get array into set of pairs using for loop and javascript map reduce functoins [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
[1,2,3,4,5,6] should be changed to set containing {1,2},{2,3},{3,4},{4,5},{5,6} using normal for loop and using javascript map and reduce functions convert array to set of pairs using different techniques Thanks in Advance
Why not a simple for loop? Array functions are great but are often unnecessary.
const arr = [1,2,3,4,5,6]
const result = []
for (let i = 1; i < arr.length; ++i)
result.push([arr[i-1], arr[i]])
console.log(result)

How can you count the number of occurrences of all of the words in a text area using Javascript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
If I had a textarea and a user pasted a paragraph into the textarea, can statistics be run on the input using JavaScript on the client side? I was thinking of using an associative array or hash map so array[word] -> # of occurrences, and iterate through word by word but I'm not sure how to do this using client side JavaScript.
I tried searching JavaScript word count but I only get results on counting the total number of words, which is not what I'm looking for. What I am looking for is more keeping a count of each specific word. Can this be done in Javascript or Jquery? If so, how should I go about doing this?
Here is an approach for you
// first get an array of words
var words = text.split(' ');
// use Array.prototype.reduce (for example) to
// create statistics
var statistics = words.reduce(function (stat, word) {
if (!stat[word]) stat[word] = 0;
stat[word]++;
return stat;
}, {});
UPDATE: A little example which handles punctuation and upper/lower case, too: http://jsfiddle.net/1pnLzv8h/1/
Something like
var arra = ['ab','pq','mn','ab','mn','ab']
function wordCount(arra,val)
{
var ob={};
var len=arra.length;
for(var k=0;k<len;k++)
{
if(ob.hasOwnProperty(arra[k]))
{
ob[arra[k]]++;
continue;
}
ob[arra[k]]=1;
}
return ob[val];
}
alert(wordCount(arra,'ab')); //output 3

How do I rearrange an array with similar items so that similar items will never neighbor each other? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
So for example if I have this array:
var input = [1,1,2,4,6,7,7,1];
I want the output to be something like:
[1,2,1,4,6,7,1,7]
The order of the new array does not matter, as long as similar items will never (or at least as seldom as possible) neighbor each other.
I can use plain JavaScript as well as underscore.js.
Try the following:
var input = [1,1,2,4,6,7,7,1];
input.sort()
var output = [];
var len = input.length;
for (var i = 0; i < Math.floor((len / 2)); i++) {
output.push(input[i]);
output.push(input[len - i - 1]);
}
if (len % 2) {
var left_over = input[Math.floor(len / 2)];
if (left_over == output[0]) {
output.push(left_over);
} else {
output.unshift(left_over);
}
}
Or see http://jsfiddle.net/d0j3Lfa3/1.
The solution sorts the numbers then alternates high and low. It deals with an odd number of elements, including corner cases such as [1,1,2] and [1,2,2] where it needs to push the middle element differently to pass. Since the input is sorted, input order doesn't affect the output.
This answer may help simplify things a bit.

Categories

Resources