How to check missing value in array of objects and add that missing value with special characters

Viewed 452

I'm currently checking the missing values of an array of objects by the object values, and that is working well if I'm using numbers or string numbers. But in some cases, the missing value will be a string number with a special character. I have tried to split the given value and to take the number, and then doing the check if that value is missing, but then I'm stuck in assigning that special character back to the value. This is the code of what I've tried so far

const one = '<0';
const two = '20+';

const data = [
    { key: 1, value: 0 },
  { key: 2, value: 0 },
  { key: 3, value: 0 },
  { key: 7, value: 0 },
  { key: 8, value: 0 },
]

const min = one.split(/([0-9]+)/);
const max = two.split(/([0-9]+)/);

const numbersArr = new Array(+max[1]);
  for (let i = +min[1]; i <= +max[1]; i++) {
    numbersArr[i] = i;
  }
  const missingLabels = numbersArr.filter(
    (itemOne) => !data.some((itemTwo) => itemTwo.key == `${min[0].length>0 && +min[1] === itemOne ? min[0] : ''}${itemOne}${max[2].length>0 && +max[1] === itemOne ? max[2] : ''}`)
  );
 missingLabels.map((item) => {
    data.push({ key: `${min[0].length>0 ? min[0].length : null}${item}`, value: 0 });
  });

console.log(data)

and the expected result should be [{key: '<0', value: 0}, {key: '1', value: 0}, ... {key: '20+', value:0}] What am I doing wrong, and how can I solve my problem? Any example will be appreciated!

1 Answers

You could match min and max and take the data into a hash table for mapping either known keys or add new objects.

For the wanted keys, you could spread an object with the new key.

const
    getValue = v => +v.toString().match(/\d+/)[0],
    one = '<0',
    two = '20+',
    data = [{ key: '<0', value: 0 }, { key: 2, value: 0 }, { key: 3, value: 0 }, { key: 7, value: 0 }, { key: 8, value: 0 }, { key: '20+', value: 0 }],
    min = getValue(one),
    max = getValue(two),
    getKey = k => ({ [min]: one, [max]: two }[k] || k),
    keys = data.reduce((r, o) => (r[getValue(o.key)] = o, r), {}),
    result = Array.from(
        { length: max - min + 1 },
        (_, i) => ({ key: null, value: 99, ...keys[min + i], key: getKey(min + i) })
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related