0

How to make function take multiple variables from an array passed in as parameter?

Edited

For example:

Achieve this:

const inputObj = [
 ['Anna', 10, 'Monday'],
 ['Anna', 15, 'Wednesday'],
 ['Beatrice', 8, 'Monday'],
 ['Beatrice', 11, 'Wednesday'],
 ['Anna', 4, 'Wednesday'],
 ['Beatrice', 5, 'Monday'],
 ['Beatrice', 16, 'Monday']
]
// expected output:
const outputObj = [ 
[ 'Anna', 10, 'Monday' ],
  [ 'Anna', 19, 'Wednesday' ],
  [ 'Beatrice', 29, 'Monday' ],
  [ 'Beatrice', 11, 'Wednesday' ] 
]

const arr = [0, 2]

const someFunction = (obj, v, a) => {
    const result = obj.reduce((acc, cur) => {
        const key = `${cur[a[0]]}|${cur[a[1]]}`
        if(!acc[key]) acc[key] = cur
        else acc[key][1] += cur[v]
        return acc
      }, {})
    return Object.values(result)
}


console.log(someFunction(inputObj, 1, arr))

with this:

const arr = [0, 2, 3, ...] // basically the array could contain any number of items.

const someFunction = (obj, v, objParams) => {
      const result = obj.reduce((acc, cur) => {
      const key = ??? 
      ...
      }, {})
}

So that the function can be reused and it accepts custom-sized arrays, check if the column numbers in the array are the same, then adds the sum of the column that is passed in as v?

How to declare the variables from the objParams to achieve the same result as the code above does?

Also how to add v in the middle of cur?

1
  • 2
    const key = objParams.join('|') seems to be what you want Commented May 30, 2018 at 0:23

2 Answers 2

1

Assuming objParams is an array of unknown size (strings in this example):

const objParams = ["c1", "c2", "c3"];
const key = objParams.join(']}|${cur[');
const built = '${cur[' + key + ']';

Built is:

${cur[c1]}|${cur[c2]}|${cur[c3]
Sign up to request clarification or add additional context in comments.

1 Comment

Actually, this doesn't work. It returns the right key but the key doesn't work. Try console.log(key), it returns the key itself as a string, not the values of the keys.
1

With ES6 you can use the spread operator in the argument definition.

More reading about spread operator on MDN

function sum(...args) {
  return args.reduce((result, value) => result + value, 0)
}

const numbers = [1, 2, 3];

console.log('sum', sum(2, 2));
console.log('sum', sum(...numbers));
console.log('sum', sum(1, 2, 1, ...numbers));

// get single args before accumulating the rest
function sum2(foo, bar, ...args) {
  return args.reduce((result, value) => result + value, 0)
}

console.log('sum2', sum2(2, 2));
console.log('sum2', sum2(...numbers));
console.log('sum2', sum2(1, 2, 1, ...numbers));

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.