problems with using array.concat()

I am attempting to reverse a stream of data using a recursive call to concatenate a return array.

The instructions for this problem are as follows: The incoming data needs to be reversed in segments that are 8 bits long.

This means that the order of these 8-bit segments needs to be reversed. For example:

11111111 00000000 00001111 10101010 (byte1) (byte2) (byte3) (byte4) should become:

10101010 00001111 00000000 11111111 (byte4) (byte3) (byte2) (byte1)

The total number of bits will always be a multiple of 8.

I have been experimenting with different combinations of approaches...

function dataReverse(data) {
  //split the incoming array into values consisting of 8 numbers each.
  var result = [];
  
  function shuffler(array){
    let input = array;
    
    if(input.length === 0){
      return result;
    } else {
      let cache = input.splice(-8,8);
      result.concat(cache);
      return shuffler(input);
    }
    return result;
  }
  
  var reversed = shuffler(data);

  return reversed;
}

console.log(dataReverse([1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]));

The expected behavior is to reverse through the input array by concatenating a result array with 8 values at a time starting from the end, without changing the order of the numbers.

My implementation above is returning an empty array. What mistake have I made?

Answer №1

It is recommended to use the join method instead of the concat method.

function reverseData(data) {
  //split incoming array into arrays with 8 numbers each
  var result = [];
  
  //recursive function for shuffling the array
  function shuffleArray(array) {
    let input = array;
    
    //base case
    if (input.length === 0) {
      return result;
    } else {
      
      //using join to concatenate 8 values at a time
      let cache = input.splice(-8, 8);
      result.push(cache.join(''));
      return shuffleArray(input);
    }
    
    return result;
  }

  var reversedData = shuffleArray(data);
  
  //reverse iterate through array and concatenate to new array
  //return result
  return reversedData;

}

console.log(reverseData([1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0]));

Answer №2

After using concat, make sure to assign the result back to a variable

result = result.concat(cache);

If you want each byte as a string of 8 characters, you can use the join method

result = result.concat(cache.join(''));

function rearrangeData(data) {
  var result = [];
  
  function shuffler(array) {
    let input = array;
    
    if (input.length === 0) {
      return result;
    } else {
      
      let cache = input.splice(-8, 8);
      result = result.concat(cache);
      return shuffler(input);
    }
    return result;
  }

  var reversed = shuffler(data);

  return reversed;
}

console.log(rearrangeData([1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0]));

You can create groups of 8 bytes each by looping over the array, then reverse and reduce them back into a single array

let rearrangeData = (data) => {
  let count = 0
  let temp = []
  let group = data.reduce((op, inp) => {
    temp.push(inp)
    if (count === 8) {
      op.push(temp)
      temp = []
    }
    return op
  }, [])
  if (temp.length) group.push(temp)
  return group.reverse().reduce((op,inp)=>op.concat(inp))
}

console.log(rearrangeData([1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0]));

Answer №3

concat method in JavaScript returns an array - make sure to assign the result:

function customDataReverse(data) {
  //breaking down incoming array into chunks of 8 numbers each.
  
  var result = [];
  
  //recursive function for shuffling
  function shuffler(array) {
    let input = array;
    
    //base case
    if (input.length === 0) {
      return result;
    } else {
      //combine 8 values at a time with the result array
      let chunk = input.splice(-8, 8);
      result = result.concat(chunk);
      return shuffler(input);
    }
    return result;
  }

  var reversed = shuffler(data);

  //reverse iterate through array and concatenate to new return array
  
  return reversed;
}

let reversedArray = customDataReverse([1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0]);

//Code for formatting output in groups of 8
reversedArray = reversedArray.reduce((acc, curr, i) => {
  const index = Math.floor(i / 8);
  acc[index] = [].concat((acc[index] || []), curr);
  return acc;
}, []);

console.log(reversedArray.map(e => e.join("")));
.as-console-wrapper {
  max-height: 100% !important;
  top: auto;
}

(This implementation is inspired by this post on Stack Overflow).

Answer №4

Divide the array into 8 sections each, then simply apply Array.reverse and Array.flat. This approach offers a functional, reusable, chain-able, and highly readable code.

Take a look at this:

let data = [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]

// custom function to segment array by quantity
const chunkBy = (arr, by=2) => arr.reduce((r,c,i) => (i%by==0 ? r.push([c]) : r[r.length-1] = [...r[r.length-1], c], r), [])

let result = chunkBy(data, 8).reverse().flat()

console.log('in:  ', data.join(''))
console.log('out: ', result.join(''))

Here is a more presentable version of the chunkBy function:

let data = [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]

const chunkBy = (arr, by=2) => // default chunk size is 2
  arr.reduce((acc, cur, index) => {
    if(index % by == 0)        // check for remainder using modulo operator
      acc.push([cur])          // start a new chunk if exact division
    else                       // continue adding to the current chunk
      acc[acc.length-1] = [...acc[acc.length-1], cur]
    return acc
}, [])

console.log(chunkBy(data, 8))

If you are using lodash, _.chunk provides this functionality:

let data = [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]

let result = _(data)
  .chunk(8)
  .reverse()
  .flatten()
  .value()

console.log(result.join(''))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

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

Information in a Service is reset upon refreshing the page

After refreshing the page (e.g., by pressing F5), I noticed that the data in my service gets cleared. Is there a way to prevent this issue without using local storage? It's not a critical feature, but it does disrupt the application flow when users re ...

Easily transfer files without the need to refresh the page by utilizing the power of AJAX

In my page file-upload.jsp, I have the following code snippet: <form action="" id="frmupload" name="frmupload" method="post" enctype="multipart/form-data"> <input type="file" id="upload_file" name="upload_file" multiple="" /> <in ...

Indeed, verifying parent.parent access

Currently, I am utilizing the yup module to validate my form. My objective is to access the parent in order to test the value. Below is my schema: enabled: yup.boolean(), contactDetail: yup.object().shape({ phoneNumber1: yup.string().nullable(), pho ...

Using an exported function with parameters as a filtering mechanism for the material datepicker

I am currently facing an issue while trying to set a const exported function in a material datepicker filter with parameters. When I try to set the parameters in my component, the function gets executed and returns the result (a boolean) instead of simply ...

Tabulate the number of items in an array based on the month and

I have received JSON data with dates indicating the creation time of multiple parcels. I want to analyze this data and calculate the total number of parcels created in each month. I am new to this process and unsure about which thread on Stack Overflow can ...

Creating randomized sequences using JavaScript

One of my hobbies involves organizing an online ice hockey game league where teams from different conferences compete. It's important to me that every team gets an equal number of home and away matches throughout the season. To simplify this task, I&a ...

What is the best way to compare dates in order to obtain the necessary results?

Question : Filter the JSON array to retrieve specific entries 1: All entries with name "Sam". 2: All entries with date "Dec 2019". // JSON Data provided below. var data = [{ "id":"27", "0":{ "name":"Sam", "date":"2021-02-28" ...

How to Transfer an Embedded Document to an Array within the Same Parent Document in MongoDB

I am working with a Mongo collection that has objects structured like this: { id: , ... events: [{},{},{} ...] ... runtime: { field1: Date, field2: Date, field3: boolean } } When a specific route is queried, I need to extract fiel ...

cdkDropList does not function properly when used with ng-template in a dynamic component list

Exploring the new Drag&Drop features introduced in Angular Material 7, I am dynamically generating components using ng-template. <div cdkDropList (cdkDropListDropped)="dropLocal($event)"> <ng-template #components></ng-templat ...

Is it possible to have more than one button for each item on my Shopping List App?

I am developing a shopping list app that allows users to add items to a list. Each item added triggers the display of a button next to it, enabling users to remove the item from the list when needed. However, a problem arises as more items are added – i ...

Getting row data from ag-grid using the angular material menu is a straightforward process

I have a specific requirement in ag-grid where I need to implement a menu to add/edit/delete row data. Currently, I am using the angular material menu component as the cell template URL. However, I am facing an issue where when I click on the menu item, it ...

Exploring the fundamentals of JavaScript within the context of Express.JS

Can you please explain the distinction between these two blocks of code in JavaScript? app.get("/api/products/1", (req, res) => { const singleProduct = products.find((product) => { product.id === 1; }); res.json(singleProduct); }) ...

I have a dynamic blog site that is generated on the fly using Ajax, making the content unsearchable

I have a blog website that is created dynamically using Ajax (XMLHttpRequest) and the HTML History API. One issue I am facing is that my content is not searchable by search engines like Googlebot. I know that Google is now able to analyze such sites, but w ...

Obtain the actual file path from a JSON response

I have set up a local express server to serve a JSON file, but I am facing an issue with displaying image files located in a local folder. The image paths are included in the JSON object that I want to display in my DOM. However, the response I receive inc ...

What is the best way to verify if a text input has a valid email format in ReactJS?

When working with ReactJS, how can I properly check if text entered in a <TextField/> component is in email format (i.e. contains @)? Since my application is connected to MongoDB, should I perform the email format validation on the client-side or se ...

Angular 2 - synchronizing timer for all users

I have developed a timer that needs to function consistently for all users at the same time. To achieve this, I stored the start_time (timestamp when the timer begins) in my database and implemented the following code snippet to calculate the remaining ti ...

Unable to Define Headers in Fetch GET Call

My current struggle involves sending a GET Request from the browser to my backend (which uses node + express). However, I am encountering issues with setting the headers properly. Below is the code snippet from the frontend: let accessToken = localStorage ...

Is there a way to toast the values of an array retrieved from a getter within my object?

My data in the format of a JSON Array looks like this and I am attempting to display the user_review_ids values - 63,59,62 using a toast message. However, instead of getting the actual values, I keep receiving what seems to be a reference to them, such as ...

Exploring through a table using JavaScript

I am struggling to search a table within my HTML for a specific term. The code I have works to an extent, but it does not account for alternatives such as searching for "what is that" when I type in "What is that". Additionally, I need the script to ignor ...

Using Typescript in NextJS 13 application router, implement asynchronous fetching with async/await

Recently, I implemented a fetch feature using TypeScript for my NextJS 13 project. As I am still getting familiar with TypeScript, I wanted to double-check if my approach is correct and if there are any potential oversights. Here is the code snippet from ...