0

I have the following object:

obj = [
    { 1: 20, 2: 26, 3: 14},
    { 1: 12, 2: 25, 3: 15},
    { 1: 14, 2: 13, 3: 19},
    { 1: 16, 2: 32, 3: 21}
]

and I want to multiply by 2 each of the positions and then add them to each position, let me explain: I multiply each value by 2 and this is the partial result:

obj = [
    { 1: 40, 2: 52, 3: 28},
    { 1: 24, 2: 50, 3: 30},
    { 1: 28, 2: 26, 3: 38},
    { 1: 32, 2: 72, 3: 42}
]

then I must add each key and add the total by adding a new array at the end inside the initial object, and this should be the final result:

obj = [
    { 1: 20, 2: 26, 3: 14},
    { 1: 12, 2: 25, 3: 15},
    { 1: 14, 2: 13, 3: 19},
    { 1: 16, 2: 32, 3: 21},
    { 1: 104, 2: 200, 3: 138}
]
1
  • A lot of the math you have given in the example is currently wrong. 32 * 2 is not 72, 40 + 24 + 28 + 32 is not 104 -- it's 124 Commented Nov 10, 2020 at 4:07

3 Answers 3

5
  • Iterate over each array object(row) using map.
  • Then for each key in that row multiply it by 2 using reduce and in the end return that row (containing result of 2's multiply)
  • While multiplying each row by 2 we also calculate the sum of key*2 for each row.
  • Push sumRow to the original object

let obj = [
  { 1: 20, 2: 26, 3: 14},
  { 1: 12, 2: 25, 3: 15},
  { 1: 14, 2: 13, 3: 19},
  { 1: 16, 2: 32, 3: 21}
]
let sumRow = {}
let partialRes = obj.map(row => Object.keys(row).reduce((acc, key) => {
  acc[key] = row[key] * 2
  sumRow[key] = sumRow[key] ? sumRow[key] + acc[key] : acc[key]
  return acc
}, {}))

obj.push(sumRow)
console.log(obj)

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

Comments

2

Using Object.keys, you can get all key of the object and using Array.prototype.forEach, you can loop the keys and do the operation as follows.

const input = [
  { 1: 20, 2: 26, 3: 14},
  { 1: 12, 2: 25, 3: 15},
  { 1: 14, 2: 13, 3: 19},
  { 1: 16, 2: 32, 3: 21}
];

const sumObj = {};
input.forEach((item) => {
  Object.keys(item).forEach((key) => {
    item[key] *= 2;
    sumObj[key] ? sumObj[key] += item[key] : sumObj[key] = item[key];
  });
});

input.push(sumObj);
console.log(input);

Comments

2

You can use Array.prototype.reduce() and push the result from that into the original array (or add it another way)

obj = [
  { 1: 20, 2: 26, 3: 14},
  { 1: 12, 2: 25, 3: 15},
  { 1: 14, 2: 13, 3: 19},
  { 1: 16, 2: 32, 3: 21}
]

console.log(obj);

obj.push(obj.reduce((acc, val) => ({
  1: acc[1] + val[1] * 2,
  2: acc[2] + val[2] * 2,
  3: acc[3] + val[3] * 2
}), {1: 0, 2: 0, 3: 0}));

console.log(obj);

Comments

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.