0

See the final codebase below. My initial approach of trying to use an array as an object was incorrect.

I'm trying to concat a string and int to look up a particular item in an array arr. The current code base console logs undefined.

Can someone explain why undefined is console logged?

Codebase in question:

const a = "T";
const b = 2;
const c = a + b;

let arr = [
        T0: 0,
        T1: 1,
        T2: 1
    ];

console.log(arr.find(e => e == c));

Thank you.

More detail (not necessary to read):

I'm trying to write code to provide an answer for an n-th Tribonacci number when inputted n.

Psuedo-code:

var tribonacci = function(n) {
  
    let arr = [
        T0 = 0;
        T1 = 1;
        T2 = 1;
    };
    
    for (i = 0; i < n + 1; i++) {
        let ("T" + (i + 3)) = ("T" + i) + ("T" + (i + 1)) + ("T" + (i + 2))
        arr.push("T" + (i + 3));
    }
    
    return arr.find(e => e == ("T" + (n + 3));

Final codebase:

Thank you, Everyone, for the feedback.

  1. I removed the "values" in the array because there are no keys & values arrays.
  2. I removed the .find() method and added a simpler way to lookup n via arr[n].
var tribonacci = function(n) {
  
    let arr = [0, 1, 1];
    
    for (i = 0; i < n - 2; i++) {
        let add = arr[i] + arr[i + 1] + arr[i + 2]
        arr.push(add);
    }
    
    return arr[n]
};
peyo
  • 351
  • 4
  • 15

1 Answers1

1

Perhaps this code will help (I may be out by one on the index, but you can fix that)

var tribonacci = function(n) {
    let arr = [0, 1, 1];
    for (i = 2; i < n; i++) {
        arr.push(arr.slice(-3).reduce((a,b) => a+b));
    }
    return arr[n];
};
console.log(tribonacci(1))
console.log(tribonacci(2))
console.log(tribonacci(3))
console.log(tribonacci(4))
console.log(tribonacci(7))
console.log(tribonacci(14))
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87