Home > Mobile >  creating an object from an alphabetically sorted array where keys are the first letters and values a
creating an object from an alphabetically sorted array where keys are the first letters and values a

Time:12-29

I've been trying to get an object output from an alphabetically sorted array.

For example, if I have arr = ['anger', 'apple', 'bowl', 'cat'] then I want my object to be like obj = { a: ['anger', 'apple'], b: ['bowl'], c:['cat']}

So far I have this, but it's not working properly.

const p4 = function (arr) {
  let val = {};
  const sortArr = arr.sort();
  for (let i = 0; i < sortArr.length; i  ) {
    for (let j = i; j < sortArr.length; j  ) {
      if (sortArr[i].charAt(0) == sortArr[j].charAt(0)) {
          val.sortArr[j].charAt(0) =sortArr[j] ;
      }
    }

    return val;
  }
};

CodePudding user response:

You can use reduce:

let arr = ['anger', 'apple', 'bowl', 'cat']

const result = arr.reduce((a, b) => {
  let c = b.charAt(0);
  if (a[c]) {
    a[c].push(b)
  } else {
    a[c] = [b];
  }
  return a;
}, {})

console.log(result)

CodePudding user response:

In the code:

let val = {};
  const sortArr = arr.sort();

sort sorts in place and returns the sorted array, so sortArr and arr both reference the same (sorted) array. You could just do:

  arr.sort()

and use arr in the following instead of sortArr.

  for (let i = 0; i < sortArr.length; i  ) {
    for (let j = i; j < sortArr.length; j  ) {

There is no need to process the array twice. All you need to do is:

  1. Iterate over each value in the array
  2. Get the first letter of the value
  3. If the val object doesn't have a property with that name, create it and assign an array to the value
  4. Push the string into the val[char] array

E.g.

function arrToObj(arr) {
  arr.sort();
  let result = {};
  for (let i=0, c; i<arr.length; i  ) {
    c = arr[i].substr(0,1);
    if (!result[c]) {
      result[c] = [];
    }
    result[c].push(arr[i]);
  }
  return result;
}

let arr = ['anger', 'apple', 'bowl', 'cat']

console.log(arrToObj(arr));

You can also do the same thing with reduce:

let arr = ['anger', 'apple', 'bowl', 'cat']

let obj = arr.sort().reduce((acc, v) => {
  let c = v.substr(0,1);
  if (!acc[c]) acc[c] = [];
  acc[c].push(v);
  return acc;
}, {});

console.log(obj);

  • Related