1

I want to convert string to bytes it worked fine if i assign value to var str as $scope.event[0] it gives me bytes only for first index ,if i assign $scope.event[] it hrows error str.charCodeAt is not a function. How can i get total bytes of the array ?

ctrl.js

    $scope.event = ["lorem ipsum", "lorem ipsum","lorem ipsum"]

     function jsonToArray() {
            var total = 0;
            var str = $scope.event;
            var bytes = []; // char codes
            var bytesv2 = []; // char codes

            for (var i = 0; i < str.length; ++i) {
                var code = str.charCodeAt(i);
                bytes = bytes.concat([code]);
                bytesv2 = bytesv2.concat([code & 0xff, code / 256 >>> 0]);
            }
            var totalBytes = 0;
            console.log('bytes', bytes.join(', '));
            for ( var i = 0 ; i < bytes.length ; i++ ) {
                totalBytes += bytes[i];
                totalCurrentBytes.push(totalBytes);
            }
            console.log('Total bytes', totalBytes);
            formatBytes(totalBytes);
        }

  jsonToArray();
hussain
  • 6,587
  • 18
  • 79
  • 152
  • [Loop through the array $scope.event...](http://stackoverflow.com/questions/1128388/looping-through-elements-of-an-array-in-java‌​script) – jonhopkins Aug 12 '16 at 16:46

1 Answers1

0

You can map/reduce the array to convert the strings to char codes. Start by running map over your keywords (we want to convert one array into another), with each word, split the word into an array so you are working with each letter and reduce that array of characters into the sum of their charCodes:

$scope.event.map(word => word.split('').reduce((total,cur) => total + cur.charCodeAt(0), 0));

Non ES6

$scope.event.map(function(word) {
    return word.split(' ').reduce(function(total, cur) {
       return total + cur.charCodeAt(0);
    }, 0);
});
Rob M.
  • 35,491
  • 6
  • 51
  • 50
  • Thanks for the answer , so my other code will remain the same ? – hussain Aug 12 '16 at 17:35
  • The code I provided only serves to calculate the sum of the charCodes for each string in the array, I'm not sure exactly what your overall goal is and what else your function does. To reiterate: an array of strings (`$scope.event`) will be turned into an array of integer sums. – Rob M. Aug 12 '16 at 17:39