Processing the data into a desired format in javaScript

Viewed 67

I am new to JavaScript and want to process the following array -

var a = [
 "John-100",
 "Mark-120",
 "John-50",
 "Mark-130"
]

into the following format -

a = {
    "John": [100, 50],
    "Mark": [120, 130]
}

But have been unable to do so. Any help will be very much appreciated.

Edit - Any other format ideas where the marks of a particular student can be grouped together are also welcome.

5 Answers

Here is one way to achieve what you described:

var a=[
 "John-100",
 "Mark-120",
 "John-50",
 "Mark-130"
]

function convertToSpecialObject(input) {
  //setup the output as an empty object
  const output = {};
  
  // iterate through input array one element at a time
  input.forEach(e => {
    // split the current element by dividing it into part[0] before the dash
    // and part[1] after the dash sign
    const parts = e.split(/-/);
    
    // now check the output object if it already contains a key for the part before the dash
    if(!output[parts[0]]) { 
      // in this case, we don't have a key for it previously
      // so lets set it up as a key with an empty array
      output[parts[0]] = []; 
    }
    
    // we must have already created a key or there is a key in existence
    // so let's just push the part after the dash to the current key
    output[parts[0]].push(Number(parts[1]));
  });
  
  // work done
  return output;
}

const b = convertToSpecialObject(a);

console.log(b);

you can achieve this by using reduce and split method

var a=[
 "John-100",
 "Mark-120",
 "John-50",
 "Mark-130"
]

const b = a.reduce((acc, val) => {
  const _split = val.split('-');
  const name = _split[0]
  if(acc && acc[name]) {
    acc[name].push(+_split[1])
  } else {
    acc[name] = [+_split[1]]
  }
  return acc;
}, {});
console.log(b)

As I suggested, string split, and array reduce - add in an array map and it's a single line of code

let a=["John-100","Mark-120","John-50","Mark-130"];

a=a.map(v=>v.split('-')).reduce((r,[n,m])=>({...r,[n]:[...r[n]||[],+m]}),{});

console.log(JSON.stringify(a));

The only answer with the correct result ... an array of NUMBERS

With Simple Approach

const input = [
  "John-100",
  "Mark-120",
  "John-50",
  "Mark-130"
];


const getCustomObject = (arr) => {

  const obj = {};
  for (let i = 0; i < arr.length; i++) {

    const split = arr[i].split('-'); //spliting with '-'

    if (obj[split[0]]) {
      //push to existing array
      obj[split[0]].push(split[1]);

    } else {
      obj[split[0]] = []; //initilize array if no member
      obj[split[0]].push(split[1]);
    }
  };

  return obj;
}

console.log(getCustomObject(input));

Now numbers are not numerical values, It can be achieved with parseInt or parseFloat

You can achieve it in a very simple way by just using a Array.forEach() method along with the String.split().

Live Demo :

var a = [
  "John-100",
  "Mark-120",
  "John-50",
  "Mark-130"
];

const obj = {};

a.forEach(element => {
  if (!obj[element.split('-')[0]]) {
    obj[element.split('-')[0]] = [];
  }
  obj[element.split('-')[0]].push(element.split('-')[1])
});

console.log(obj);

Related