Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript Getting the sum of equal array elements, and creating a new array

jaredcb

New Coder
I'm scratching my head over this one. Not sure if I'm asking this question wrong, but I'm trying to reach out where I can hopefully find someone who knows what I can try. I tried asking this on another forum, and they didn't like that I didn't have any example of failed code yet, so they wouldn't help. The trouble is, I don't even know what code I would try here, or where to begin. So I'm kinda stuck. Here's the problem:

I have two arrays, with the same lengths, which reference each other, and I need to use both arrays to create a new third array. The first array contains names, the second contains numbers assigned to each name. The Name Array has several instances of repeating names (and some that are listed only once).

So what I am trying to do is build a new array that uses this logic: Take the sum of any group of repeating names, as they appear in sequence, and assign the sum to its own element in the new array, then move on to the next.

For example:

Code:
nameArray = [Jack, Jack, Jack, Betty, Tim, John, John, Jack, Jack]

numberArray = [2, 3, 7, 3, 5, 6, 1, 4, 5]

So Jack is 2+3+7, Betty is 3, Tim is 5, John is 6+1, and Jack is 4+5.

Then the new array should look like this:

Code:
newArray = [12, 3, 5, 7, 9]

But I can't seem to figure out how to achieve this. Any ideas?

Again, if I'm not asking this correctly, I apologize. I'm just pulling my hair out a bit with this one. Any insight is appreciated.
 
You are asking the question correctly, the problem is clear. But the guys on the other forum are quite right - if you have not tried anything at all you are not going to get help. It works the same here. Surely you must have some idea of how to approach this.... Even if it is only some pseudo code or plain text describing your algorithm.
 
I could not post yesterday because of routine maintenance to this forum. When I saw this -> nameArray = [Jack, Jack, Jack, Betty, Tim, John, John, Jack, Jack]
I knew you didn't know enough to work with arrays. Arrays are not easy to understand, as is working with strings, And just when you think you have it down along comes JSON. Damn!
Items placed in an array must be strings or numbers. Jack must be "jack", in quotes to make it a string when placed in an array. In my first attempt at this I added all numbers for Jack, which sounded normal to me. And I think I still have a bit of that code if you want it - but you must act fast, too long and I will delete it.
Doing things the way you want was a bit harder. Go here to see the explanations. https://www.w3schools.com/js/js_array_methods.asp and if you need to see one in action - go here https://www.w3schools.com/jsref/jsref_obj_array.asp

Here's the code:
Code:
<!DOCTYPE html>
<html>
<head>
<title>Table Example</title>
<style></style>
</head>
<body>
<p id='demo'></p>
<script>
var nameArray = ["Jack", "Jack", "Jack", "Betty", "Tim", "John", "John", "Jack", "Jack"];
var numberArray = [2, 3, 7, 3, 5, 6, 1, 4, 5];
var newArray = [];
var total = numberArray[0];
var arrayTotal = nameArray.length;

for (let index = 0; index < arrayTotal; index++) {
    if(nameArray[0] != nameArray[1]){
        nameArray.shift();
        numberArray.shift();
        newArray.push(total);
        total = numberArray[0];
    }else{
        total += numberArray[1];
        nameArray.shift();
        numberArray.shift();
    }
}
document.getElementById('demo').innerHTML = newArray;
</script>
</body>
</html>
 
Ingenious solution. I had something similar but used an extra if to check for end of the array. You sneakily refer to an element just beyond the array, relying on JS to return undefined rather than throwing an exception like any language would do. Nice trick, though I would not recommend it to a novice. Also I think that looping through wo arrays by shifting them all the time is an expensive way of doing things. Probably doesn't matter for small arrays, but just imagine doing this on a huge array. I could be wrong though, perhaps shifting is nothing more than moving a pointer.
I would post my solution but I don't agree with giving someone the complete working code if they are not showing any initiative to try something themselves.
 
When I was working on this I thought about making a temp array and then deleting elements from it preserving the original array, but decided that
didn't matter cause we have the original in the code.
What I thought was the tricky part was doing the comparison as a negative. I did spend a lot of time working on it from the 'is equal' comparison. When I went with the neg results things went fast and smooth.

Thanks for feedback cbreemer. Much appreciated
 
Well, since the OP now already has a piece of working code I may as well post my solution too. Let's spoil them some more and hope it is educational 😀

JavaScript:
let nameArray = ['Jack', 'Jack', 'Jack', 'Betty', 'Tim', 'John', 'John', 'Jack', 'Jack'];
let numberArray = [2, 3, 7, 3, 5, 6, 1, 4, 5];
let lastname = nameArray[0];
nameArray.push("-");
let newArray = [];
var sum = 0;

for (let i=0; i<nameArray.length; i++)
{
    let name = nameArray[i];
    let num  = numberArray[i];

    if ( name == lastname )
    {
        sum += num;
        continue;
    }

    newArray.push(sum);

    if ( name == '-' )
        break;

    sum = num;
    lastname = name;
}

console.log(newArray);
 
JavaScript:
const nameArray = ['Jack', 'Jack', 'Jack', 'Betty', 'Tim', 'John', 'John', 'Jack', 'Jack'],
         numberArray = [2, 3, 7, 3, 5, 6, 1, 4, 5];
   let res = [];
  
   nameArray.forEach( (n, i, ar) =>
                          n != ar[ i - 1 ] ?
                             res.push( numberArray[i] ) :
                                res[ res.length - 1 ] += numberArray[i]
                    );
  
   console.log( res ); // [12, 3, 5, 7, 9]
 
Thank you all for your help. I had a full load of work this weekend and am just now able to get back and look at your responses.

I'm sorry if it appeared that I wasn't "showing any initiative", as I can confidently say I have been spending a lot of time searching for the answer to this and yes, trying to solve it myself. I had done some other code earlier in this same project for a similar need (in that case, it was cycling through the array, comparing the names before & after each, and using that information to create a new array based on conditions for if the names were the same or not), and I did try adapting that solution to this problem, but adding in the number array and the inclusion of getting multiple sums of multiple groupings was what kept tripping me up. I was struggling to wrap my mind around it. I did try. I just felt that my efforts were nearly laughable in how obvious it was that they weren't going to work, that I didn't really see the point of sharing them. Either way, I'd have been setting myself up for some ridicule here I guess. I wasn't necessarily asking to be handed complete working code either. Honestly just some advice or insight would've been appreciated. It's been a long and tiresome couple of weeks for me for more reasons than this, and I was really just needing some help here when I was sorta at the end of my rope. Sorry if you were offended however, by what you perceived as a lack of motivation.

Again, thank you for the help & insight offered. It definitely helped and was indeed educational.
 
If only you had posted what you had done, and explained where you got stuck ! It seems you had something going but hit some particular roadblock, which surely someone would have helped with. Contrary to what you thought, there is no shame in posting code that is obviously wrong 😉
 

New Threads

Buy us a coffee!

Back
Top Bottom