Convert one array into two arrays along with some actions

Hi Guys,

I have an array like as input fields and that needs to convert in two arrays like an output using javascript, please suggest something.

Input:
Dimension = [“300x600”,“160x600”,“320x250”]
Output:
width = [300,160,320]
height = [600,600,250]

You can split a string using the split() method.

And then you can create two new arrays in which to copy the things, converting to number in the process.

An Efficient solution is to first compute the sum of the whole array from left to right. Now we traverse array from right and keep track of right sum, left sum can be computed by subtracting current element from whole sum.

Below is the implementation of above idea.

  • C++
  • Java
  • Python3
  • C#
  • PHP

filter_none

edit

play_arrow

brightness_4

// C++ program to split an array into Two

// equal sum subarrays

#include<bits/stdc++.h>

using namespace std;

// Returns split point. If not possible, then

// return -1.

int findSplitPoint( int arr[], int n)

{

// traverse array element and compute sum

// of whole array

int leftSum = 0;

for ( int i = 0 ; i < n ; i++)

leftSum += arr[i];

// again traverse array and compute right sum

// and also check left_sum equal to right

// sum or not

int rightSum = 0;

for ( int i=n-1; i >= 0; i--)

{

// add current element to right_sum

rightSum += arr[i];

// exclude current element to the left_sum

leftSum -= arr[i] ;

if (rightSum == leftSum)

return i ;

}

// if it is not possible to split array

// into two parts.

return -1;

}

// Prints two parts after finding split point using

// findSplitPoint()

void printTwoParts( int arr[], int n)

{

int splitPoint = findSplitPoint(arr, n);

if (splitPoint == -1 || splitPoint == n )

{

cout << "Not Possible" <<endl;

return ;

}

for ( int i = 0; i < n; i++)

{

if (splitPoint == i)

cout << endl;

cout << arr[i] << " " ;

}

}

// driver program

int main()

{

int arr[] = {1 , 2 , 3 , 4 , 5 , 5 };

int n = sizeof (arr)/ sizeof (arr[0]);

printTwoParts(arr, n);

return 0;

}

Output :

1 2 3 4 5 5

If you want to keep this as one operation, put the output in an object – so return an object like {widths: [1, 2, 3], heights: [3, 5, 1]}. Then you can have a single function that returns both of your arrays at once.

Example solutions, first using a loop, (very similar to idiomatic Python rather than JS):

function parseDimensions(dimensions) {
  const widths = [];
  const heights = [];

  for (const dimension of dimensions) {
    // Assuming it is always `WIDTHxHEIGHT`
    const [width, height] = dimension.split('x').map(d => parseInt(d, 10));
    widths.push(width);
    heights.push(height);
  }

  // Returns an object with the two arrays under `widths` and `heights` keys:
  return { widths, heights };
}

Or more idiomatic JavaScript, using the reduce method:

function parseDimensions(dimensions) {
  // This is the object that will be filled and output by the reduce operation:
  const accumulator = { widths: [], heights: [] };

  return dimensions.reduce(({widths, heights}, dimension) => {
    const [width, height] = dimension.split('x').map(d => parseInt(d, 10));

    return {
      widths: widths.concat(width),
      heights: heights.concat(height)
    };
  }, accumulator);
}

Both return an object containing your two arrays:

> const {widths, heights} = parseDimensions(["300x600","160x600","320x250"])
> widths
[300, 160, 320]
> heights
[600, 600, 250]

I did it this way… Hope it helps.

function convertMultipleArray(arr){

var width = [];
var height = [];
arr.forEach(function(item){

item.split(‘x’).forEach(function(elem,index){

  index == 0 ? width.push(elem) : height.push(elem);

});
});

return "Width Arr = " + width + ", Height Arr = " + height;

}

alert(convertMultipleArray([‘300x600’,‘160x600’,‘320x250’]));

Similar to @DanCouper 's reduce, just not bothering with the object. As he said, a JavaScript function will only return one thing. In order to get “two” things you either return an object with two properties or an array with two elements. They both work as well as each other, it just depends on how you are planning on using the data (and object properties can be easier to follow from a code reading standpoint):

const dimensions = ["300x600", "160x600", "320x250"];

function parseDimensions(arr) {
    return arr.map(dim => dim.split('x'))
        .reduce((acc, curr) => {
            acc[0].push(+curr[0]);
            acc[1].push(+curr[1]);
            return acc;
        }, [ [], [] ]);
}

const [widths, heights] = parseDimensions(dimensions);
1 Like