1

I'm trying to create a function which will replace array values with its matching object value. I've tried using .filter. However, it will not allow for duplicate values as seen in the example below.

Current code

        fetchInventory: async function () {
            await Object.entries(this.$store.state.inventory).forEach(([k, v]) => {
                for (let i = 0; i < parseInt(v); i++) this.inventory.push(parseInt(k))
            })

            const items = JSON.parse(localStorage.getItem('priceCache'));
            const filteredItems = await items.list.filter(i => this.inventory.includes(i[0]));

            this.inventory = await filteredItems;
        }

Input var array = [1208, 1209, 1209]

Current output

var output = [[1208, 'returned item'], [1209, 'returned item']]

Expected output

var output = [[1208, 'returned item'], [1209, 'returned item'], [1209, 'returned item']]

localStorage Object const items = JSON.parse(localStorage.getItem('priceCache'));

10
  • Where are you using array? Commented Jul 10, 2020 at 3:54
  • On another note, Wonder if await is required in each of those lost two lines. Commented Jul 10, 2020 at 3:55
  • 1
    Try [1208, 1209, 1209].map(e => [e, 'returned item']) Commented Jul 10, 2020 at 3:55
  • Its coded in vue, in the first part I'm pushing values to data array, @User863 I like where your headed but 'returned item' is just placeholder, there are dynamic values for each number. Commented Jul 10, 2020 at 3:58
  • Where are you getting these dynamic values? Please provide all the relevant information so we can help you. Commented Jul 10, 2020 at 3:59

2 Answers 2

1

It looks like you want Array#map and Array#find.

this.inventory = this.inventory.map(v=>[v, items.list.find(x=>x[0]===v)[1]);
Sign up to request clarification or add additional context in comments.

1 Comment

@Shimsho No problem.
0

I guess you don't want filter to lose any of the values in array (1209 here, for example)

So what you actually need is map first and then filter:

var items = [1208, 1209] 
// inventory
var array = [1208, 1209, 1209] 
// filtered inventory
var output = array.map(i => items.includes(i) ? [i, 'returned item'] : undefined)
  .filter(i => i !== undefined)

console.log(output)

/** output:
(3) [Array(2), Array(2), Array(2)]
0: (2) [1208, "returned item"]
1: (2) [1209, "returned item"]
2: (2) [1209, "returned item"]
**/

3 Comments

Why not simply this? var array = [1208, 1209, 1209]; var res = array.map(i=> [i, "returned value"]); console.log(res)
Because he has to filter according to the inventory from the code he posted.
It's not very clear because they have just defined the input like this var array = [1208, 1209, 1209];

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.