# Why doesn't my test() return an object?

Why doesn’t my test function return an object when it is called?
I edited my test function with help from @JeremyLT 's comment.

``````function sumCommon(...Args) {
const arrElAndArgsIndexArr = Args.map((el,i) => el = el.map(e => e = [e,i]));
const arrElAndArgsIndexArrFlatSorted = arrElAndArgsIndexArr.flat().sort().sort((a,b) => a[1] - b[1]);
let zeroToAllArgsElLength = 0;
let innerIndex = 0;
let sumArr = [];
while(zeroToAllArgsElLength !== arrElAndArgsIndexArrFlatSorted.length * arrElAndArgsIndexArrFlatSorted.length){
if(zeroToAllArgsElLength + 1 % arrElAndArgsIndexArrFlatSorted.length === 0){
innerIndex = -1;
}
innerIndex += 1;
zeroToAllArgsElLength += 1;
for(let i = 0; i < arrElAndArgsIndexArrFlatSorted.length; i++){
if(arrElAndArgsIndexArrFlatSorted[innerIndex][0] === arrElAndArgsIndexArrFlatSorted[i][0] && arrElAndArgsIndexArrFlatSorted[innerIndex][1] !== arrElAndArgsIndexArrFlatSorted[i][1]){
if(i !== innerIndex) sumArr.push(arrElAndArgsIndexArrFlatSorted[i][0]);
}
}
}
return sumArr.reduce((acc,el) => acc + el, 0);
}

function test(){
const testResultsObject = {};
testResultsObject.test1 = sumCommon([1, 2, 3], [5, 3, 2], [7, 3, 2]) === 5? "passed": "failed";
testResultsObject.test2 = sumCommon([1, 2, 2, 3], [5, 3, 2, 2], [7, 3, 2, 2]) === 7? "passed": "failed";
testResultsObject.test3 = sumCommon([1], [1], [1]) === 1? "passed": "failed";
testResultsObject.test4 = sumCommon([1], [1], [2]) === 0? "passed": "failed";
testResultsObject.test5 = sumCommon([1, 2, 2, 3, 2], [5, 3, 2, 2, 1], [7, 3, 2, 2, 1]) === 8? "passed": "failed";
return testResultsObject;
}
``````

Side note - using a ternary like this is an anti-pattern. A ternary isn’t a replacement for if statements.

Now, if you wrote

``````obj.test1 = sumCommon(...) === 5 ? 'pass' : 'fail';
``````

That would not be an anti-pattern.

Though `obj` is a variable name no-no. Maybe `results`?

1 Like

Hi, problem-solver,

Whenever this happens, I will add a bunch of console.log() statements in the same location where it’s going wrong.

In your code, the `innerIndex` becomes 9 at the very end, which is not an index within the `arrElAndArgsIndexArrFlatSorted` array. The array only goes up to 8 (although the length is 9).

You should refine your while statement and if statements to account for non-existing indices within an array and do not try to call the array at those indices if those indices do not exist.

1 Like