0

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)
    }
  }
}
thanksd
  • 54,176
  • 22
  • 157
  • 150
JonathanMitchell
  • 400
  • 1
  • 2
  • 12
  • and what do you like to achieve? – Nina Scholz Jan 04 '16 at 21:47
  • Your first section of code works as expected, so I'm not sure what your question is (https://jsfiddle.net/vr34gqyw/) – thanksd Jan 04 '16 at 21:50
  • You can split each member on the hypen (-), the split each number and add the bits, e.g. `'818'.split('').reduce(function(a, b){return +a + +b})` returns `17`. Do you want to add all the digits in `"818-625-9945"` or just those in each sequence, e.g. `"818", "625", "9945"`? – RobG Jan 04 '16 at 21:50
  • It seems to me you're looking for the number with the most 8s. That would be 888-222-2222, is that the answer you're looking for? – RobG Jan 04 '16 at 22:18

2 Answers2

1

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • The more natural (subjective) construction for the `array -> scalar` transformation is `Array.prototype.reduce`. That way you switch back to pure functions :-) – zerkms Jan 04 '16 at 22:01
  • Code only answers aren't that helpful. You need to explain how it works and why it answers the OP's question (which is not clear). Also, there is no need for *map*. – RobG Jan 04 '16 at 22:07
  • I still don't see how this answers the question. I think the OP wants the number with the most 8s in it (but I am not certain of that), which is 888-222-2222, but the OP says the result should be 818-625-9945. In that case, you can just use reduce and *match* on 8, the one that gets the most matches wins. – RobG Jan 04 '16 at 22:22
  • 1
    @RobG, so any answer will be speculation, what the op want. – Nina Scholz Jan 04 '16 at 22:26
  • Yes, you can take a guess (or two), however the preferred strategy is to not answer the question until it's clear what the OP wants. – RobG Jan 04 '16 at 22:40
0

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);
Icepickle
  • 12,689
  • 3
  • 34
  • 48
  • You can save yourself an iteration by `var charSum = split(/-|\s*/.reduce(function(a,b) return +a + +b))`. However, it's not clear what the OP wants so whether this actually answers the question or not is moot. – RobG Jan 04 '16 at 22:38
  • @RobG: true, that's why i choose a rather long form of replying to show which approaches he could use :D maybe I should have commented my code a bit more, but I guess we'll see what the OP wants – Icepickle Jan 04 '16 at 23:28