What is the process of transferring values from a 1-dimensional array to a 2-dimensional array in JavaScript?

Hello everyone, I am new to this forum and a budding programmer. Currently, I am working on developing an app that can translate binary strings into English sentences. Here is the code snippet that I have been working on:

function binaryAgent(str) {      

  var binArr = str.split('');
  var res = [];
  var binary = [128, 64, 32, 16, 8 , 4, 2, 1];
  var k = -1;
  var matrix = [];
  var noSpace = str.replace(/\s+/g, '');

  for(var m=0; m<noSpace.length; m++){
      if(m % 8 === 0){
        k++;
        matrix[k] = []; 
      }
        matrix[k].push(noSpace[m]); 
  }

  for(var i=0; i<matrix.length; i++){
    for(var j=0; j<matrix[i].length; j++){
      if(matrix[i][j] == 1){
        res.push(binary[j]);
      }
    }
  }

  return res;
}

binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 001000 
            01100010 01101111 01101110 01100110 01101001 01110010 011001 
            01100011 01101111 01110011 00100000 01100110 01110101 011010
            01101110 00100001 00111111");

In the second loop, I search through the 'matrix' array to identify values of 1. When found, I push the corresponding value from the 'binary' array. However, I have encountered a roadblock in one particular area.

The function returns an array 'res' containing all the values combined together:

[64, 1, 64, 32, 16, 2, 64, 32, 4, 1, 64, 32, 8, 4, 2, 32, 4, 2, 1, 64, 32, 16, 4, 32, 64, 32, 2, 64, 32, 8, 4, 2, 1, 64, 32, 8, 4, 2, 64, 32, 4, 2, 64, 32, 8, 1, 64, 32, 16, 2, 64, 32, 4, 1, 64, 32, 16, 2, 1, 32, 64, 32, 4, 2, 64, 32, 16, 4, 1, 64, 32, 8, 4, 2, 32, 1, 32, 16, 8, 4, 2, 1]

The problem lies in my inability to figure out how to sum the appropriate values within the 'res' array. My desired outcome would look something like this:

[[64, 1], [64, 32, 16, 2], [64, 32, 4, 1], [64, 32, 8, 4, 2] etc ..]

This would allow me to add up the values within each array and later utilize the fromCharCode() function to transform them into an English sentence.

Does anyone have a suggestion on how I can achieve an array structure like mentioned above? Or perhaps an alternate method to sum the relevant values?

Answer №1

If I grasp the nature of your issue correctly, you could apply a similar tactic in your second loop. Create a new array within res before commencing the inner loop, and then insert values into that array during the inner loop:

function convertToBinary(str) {

      var binArray = str.split('');
      var result = [];
      var binaryValues = [128, 64, 32, 16, 8 , 4, 2, 1];
      var index = -1;
      var binaryMatrix = [];
      var noSpaceStr = str.replace(/\s+/g, '');

      for(var n=0; n<noSpaceStr.length; n++){
          if(n % 8 === 0){
            index++;
            binaryMatrix[index] = [];
          }
          binaryMatrix[index].push(noSpaceStr[n]);
      }

      for(var x=0; x<binaryMatrix.length; x++){
        result[x] = []
        for(var y=0; y<binaryMatrix[x].length; y++){
          if(binaryMatrix[x][y] == 1){
            result[x].push(binaryValues[y]);
          }
        }
      }
      return result;
    }

var output = convertToBinary("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");
console.log(output)

On an additional note, although not specifically inquired about, you can streamline the code by removing some of the loops:

function simplifyBinaryConversion(str) {
      var binaryValues = [128, 64, 32, 16, 8 , 4, 2, 1];
      var index = -1;
      var binaryMatrix = str.split(/\s+/).map(i => Array.from(i))

      return binaryMatrix.map(arr => arr.reduce((acc, curr, i) => {
        if(curr == 1) {
            acc.push(binaryValues[i])
        }
        return acc
      }, []))
    }

var simplifiedOutput = simplifyBinaryConversion("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");
console.log(simplifiedOutput)

Answer №2

Check out this completed application:

function convertBinaryToString(str) {

  var binaryString = str.split('');
  var results = [];
  var binaryValues = [128, 64, 32, 16, 8 , 4, 2, 1];
  var index = -1;
  var bitMatrix = [];
  var noSpaces = str.replace(/\s+/g, '');
  var sums = [], charResults = [], finalResult = [];

  for(var m=0; m<noSpaces.length; m++){
      if(m % 8 === 0){
        index++;
        bitMatrix[index] = []; 
      }
        bitMatrix[index].push(noSpaces[m]); 
  }

  for(var i=0; i<bitMatrix.length; i++){
    results[i] = [];
    for(var j=0; j<bitMatrix[i].length; j++){
      if(bitMatrix[i][j] == 1){
        results[i].push(binaryValues[j]);
      }
    }
  }

  function calculateSum(total, num){
    return total + num;
  }

  for(var x=0; x<results.length; x++){
    for(var y=0; y<results[x].length; y++){
     sums[x] = results[x].reduce(calculateSum);
    }  
  }

  for(var z=0; z<sums.length; z++){
    charResults[z] = String.fromCharCode(sums[z]);
  }

  finalResult = charResults.join('');

  return finalResult;
}

convertBinaryToString("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");

I understand that the code may not be perfect, but I have gained valuable knowledge today. Special thanks to Mark_M once more!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging AngularJS for retrieving the total number of elements in a specific sub array

I'm currently working on a to-do list application using Angular. My goal is to show the number of items marked as done from an array object of Lists. Each List contains a collection of to-dos, which are structured like this: [{listName: "ESSENTIALS", ...

What is the predefined value for a multi-select generated by the ng-for directive in Angular?

I am having trouble setting default selected values for the multi-select. Despite trying various methods such as initializing the ngModel to bind the variable and using [selected] = "selectedSegment == 'S1'", none of them seem to be effective fo ...

Executing $(this).parent().remove() triggers a full page reload

A unique feature of my webpage is that with just a simple click of a button, users have the ability to dynamically add an endless number of forms. Each form contains fields for user input and also includes a convenient delete button. var form = " Name ...

Implement the CSS styles from the Parent Component into the Child Component using Angular 6

Is there a way to apply CSS from the Parent Component to style the child component in Angular 6? Please advise on how to approach this issue. How can we inherit the css styles from the Parent Component? <parent> <child> <p>hello ...

Dynamic content loading for Twitter Bootstrap Popover using Ajax

Below is my code for dynamic content loading in a popover using AJAX. The popover displays correctly after the initial load, but there is an issue with its behavior on the first "show" event – it appears and disappears immediately. $("a.mypopover"). ...

Issue with opening image modal when clicking on images, JavaScript seems to be malfunctioning

I created a gallery of modal images that I want to open when clicked, but for some reason it's not working as expected. What I'm trying to achieve is passing the image ID of each image to JavaScript when they are clicked so that the script can th ...

Guide to creating and importing a JSON file in Wordpress

I'm looking to save a list in a JSON file within the Wordpress functions.php file. Can you guide me on how to achieve this? function ScheduleDeletion(){ ?> <script type="text/javascript"> var day = (new Date).get ...

Is it possible to delete a route if the .remove function is not available?

Hey there, I'm having an issue with a route I created to delete a product. Every time I try to run it, I'm getting an error message that says .remove is not a function. I've been searching for a solution but haven't been able to fix it. ...

Sending MVC3 model information as JSON to a JavaScript block

My challenge is to correctly pass my MVC3 model into a script block on the client side. This is the approach I'm taking in my Razor view: <script type="text/javascript"> var items = @( Json.Encode(Model) ); </script> The "Model" in t ...

comparing jquery version 1 and jquery version 3 backward-compatible browsers

It has come to my attention that jquery 2.x does not offer support for legacy browsers. If I wish to accommodate those outdated Internet Explorer versions, I must resort to using jquery 1.x. However, I am curious about jquery 3.x. Does it provide support ...

What could be causing my external JavaScript file to not function properly upon loading my HTML file?

I have organized my code by separating the HTML and JavaScript portions. The JavaScript code is now in its own separate file and I use 'script' tags to reference it in the HTML file. Within the JavaScript code, I have two functions - one creates ...

Bring the element into view by scrolling horizontally

I am facing a challenge with a list of floated left divs inside another div. This inner block of divs can be hovered over to move it left and right. Each inner div, known as 'events', has class names that include a specific year. Additionally, t ...

Application of id missing on all buttons in Bootstrap tour template

I'm having an issue with applying a new id to the next button in a Bootstrap tour template. I added the id to the button, but it only seems to work for the first stage and not the subsequent ones. Can anyone provide insight into why this might be happ ...

Experiencing issues with iOS Annotations and Arrays causing Bad Access errors

Here is a code snippet that utilizes MKLocalSearch to conduct a search and load the results into an array. Everything works smoothly until there is an attempt to dismiss the viewcontroller by tapping the back button on the navigation bar, resulting in an ...

Show a message of 'no results found' when implementing a jQuery plugin for filtering items in a list

I recently implemented the 'Filtering Blocks' tutorial from CSS-Tricks to filter items by category on an events website I'm developing. While the filtering functionality works perfectly, I realized that there is no mechanism in place to sho ...

An object is not defined in the following scenario

I currently have a custom function that includes the following code snippet: 1: var object = get_resource($scope, CbgenRestangular, $stateParams.scheme_id); 2: console.log(object) This function triggers the following code: get_resource = function ($sc ...

Is there a way to create a dynamic gallery using Magnific Popup that showcases both images and an iframe video together?

One way I am utilizing magnific popup is to set up an image gallery using the code snippet below: $('.main-content').magnificPopup({ delegate: '.gallery', // selecting child items to open in pop-up when clicked type: 'image&ap ...

Why is the JavaScript code not functioning when the page loads?

Here is the HTML code snippet: <head> <link href="/prop-view.css" media="screen" rel="stylesheet" type="text/css"> <script src="/javascripts/jquery-1.3.2.min.js" type="text/javascript"></script> <script type="tex ...

Can saving data within a mongoose pre-save hook initiate a continuous loop?

Currently, I am developing an API for a forum system which includes functionalities for users, forums, and posts. In my MongoDB Database, there is a 'categories' collection where each category acts as a container for a group of forums. Each categ ...

What are the different ways to interact with the object retrieved from the onloadedmetadata event

Having trouble accessing a specific value in an object that is the result of the onloadedmetadata event. When I log the entire object using audioDuration, I am able to see and retrieve the respective value without any issues. However, when I try to access ...