Home > database >  Processing the data into a desired format in javaScript
Processing the data into a desired format in javaScript

Time:06-22

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. TIA!

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

CodePudding user response:

Here is one way to achieve what you described:

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

function convertToSpecialObject() {
  //setup the output as an empty object
  const output = {};
  
  // iterate through input array one element at a time
  a.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(parts[1]);
  });
  
  // work done
  return output;
}

const b = convertToSpecialObject(a);

console.log(b);

CodePudding user response:

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],r),{});

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

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

CodePudding user response:

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)

CodePudding user response:

With Simple Approach

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


const convert = (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(convert(input));
  • Related