1

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.

1
  • the use of var makes me wonder if you're bound to an older version of javascript. Also Are you sure you want to reassign the new object to the same variable? Could clarify these things? Commented Jun 22, 2022 at 5:55

5 Answers 5

2

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);

Sign up to request clarification or add additional context in comments.

2 Comments

The numbers are strings...
@LeeTaylor Thanks. I fixed my code to reflect your notice
1

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)

1 Comment

The numbers are strings....
1

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);

Comments

1

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

Comments

1

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

2 Comments

spread the accumulator and avoid returning assignment =>({ ...r , [n] : [...r[n] || [], +m] })
yeah, OK - I always forget that step

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.