0

I am trying to get the index of last non empty name in my array of objects. I tried the code below:

var myArray = [{'name':''},{'name':'b'},{'name':''}];
var last = myArray.reduce((acc, curr) => curr ? curr : acc);
console.log(myArray.lastIndexOf(last))

The log always displays 2. The output should be 1 since name == 'b' is not empty. How can I correct this code?

2 Answers 2

2

curr is always an object in your case, and objects are always truthy. You should not check for the value of curr, but of curr.name.

var myArray = [{'name':''},{'name':'b'},{'name':''}];
var last = myArray.reduce((acc, curr) => curr.name ? curr : acc);
console.log(myArray.lastIndexOf(last));

You could as an alternative also use reverse and find:

var myArray = [{'name':''},{'name':'b'},{'name':''}];
var last = [...myArray].reverse().find(curr => curr.name);
console.log(myArray.lastIndexOf(last));

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

Comments

1

You could easily use a traditional loop to do that

 var myArray = [{'name':''},{'name':'b'},{'name':''}];
  
  function lastIndex(arr, ppty){
    // Start transversing the array from the rear
    // Improve your time complexity
    for (let i = arr.length - 1; i >= 0; i--) {
      if(arr[i][ppty]){
        return i
      }
    }
    return false // Return false if it's not found
  }

const index = lastIndex(myArray, 'name') // This should give your answer

console.log(index)

4 Comments

Wouldn't this for (let i = arr.length; i > 0; i--) be for (let i = arr.length-1; i >= 0; i--)
Yes.. I made an error there.. it should be arr.length - 1.. i will update it thanks
you are closer.. but don't you want to go all the way to index zero? for (let i = arr.length-1; i >= 0; i--)
An oversight on my end

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.