Inventory update solution

Hi everyone! I’m new in Javascript and I’d like to share with you my solution to this challenge.
It’s not elegant but it works. And I did it with no help. I’m open to all critics and comments to make it better.
Thanks you all in advance :relaxed:



function updateInventory(arr1, arr2) {
  //tenporal array for items names
    let temp = [];
    for(let i=0; i<arr1.length; i++){
    //loop through new delivery and push it to arr1 if not exist or adding if if exists => {
        if(!temp.includes(item[1])) {
            let index = temp.indexOf(item[1]);
            arr1[index][0] += item[0];
//return sorted inventory
    return arr1.sort(function(a, b){
        if(a[1] > b[1]){
            return 1;
        } else if(a[1]< b[1]){
            return -1;
        } else {return 0}

// Example inventory lists
var curInv = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [1, "Hair Pin"],
    [5, "Microphone"]

var newInv = [
    [2, "Hair Pin"],
    [3, "Half-Eaten Apple"],
    [67, "Bowling Ball"],
    [7, "Toothpaste"]

console.log(updateInventory(curInv, newInv));

HI @elb.qqq !

Welcome to the forum!

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Oh thanks you! I uploaded it from my mobile and I couldn’t format it. :grin::muscle:

You are not using map correctly (When not to use map()). It returns a new array. If you just want to loop an array and push to an array inside it use forEach instead. Also, just know that sort is in place and will mutate the array, so making a copy to sort is often advisable.

When I looked for the solution on the guide, I wondered why they’ve chosen for each, now I get it. Thanks you for answering!
What do you think about the algorithm with those modifications?:grimacing:

A post was split to a new topic: Please provide feedback on my inventory update solution