0

I have an object where I store words, their pronunciation, type, description usage and number of favorites.

Words: {
  word: string,
  pronunciation: string,
  type: string,
  description : string,
  usage: string,
  favorites: number
}[] = [];

First I get the Words out of local storage with and assign them to a new object.

Then I sort those words by favorites so the word with most favorites is top on the list.

this.storage.get('words').then((val) => {
  this.Popular = val;
  this.Popular.sort(function (a,b) {return b.favorite - a.favorite});
}

When the user clicks on the word I want to get the index of that word in the original unsorted object.

So I get the original object again out of the storage.

Then I'm trying to get the original id of the word with indexOf but I always get -1 despite the selected word being in the original object.

this.storage.get('words').then((val) => {
  this.Words = val;
  var index = this.Words.indexOf(selectedWord);
  console.log(index);
}

selectedWord is a word selected from the sorted list:

Word: {
  word: string,
  pronunciation: string,
  type: string,
  description : string,
  usage: string,
  favorites: number
}

What am I doing wrong? How can I get the index of the selected word from the original unsorted object?

Lukozaver
  • 65
  • 1
  • 1
  • 6
  • Please share a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – Ele Mar 07 '18 at 17:45
  • 1
    indexOf with objects, as far as I remember, checks with **reference**. Are you sure you are using the **exact same object reference?** otherwise, it will return -1. If that's not the same reference but you're 100% sure that works are unique, you may use. `var index = this.words.indexOf(this.Words.find( w => w.word === selectedWord.word));`. Where is **selectedWord** coming from? Your code, in any case, will likely **always fail**, because this.Words is being assigned slightly before searching the data, so I assume that all references are changing, hence the -1. – briosheje Mar 07 '18 at 17:47
  • and what is selectedWord? – dfsq Mar 07 '18 at 17:48
  • @dfsq added the description of selectedWord. It's just an object selected from the sorted list. – Lukozaver Mar 07 '18 at 18:46

0 Answers0