Inventory Update

freeCodeCamp challenge

by Vadim Costin

JavaScript

//jshint esversion: 6
function updateInventory(arr1, arr2) {
    // All inventory must be accounted for or you're fired!
  for(let i=0; i< arr1.length; i++){
    let searchFilterExist = arr2.filter(invElement => {
      return invElement[1] === arr1[i][1];
    });
    
    if(searchFilterExist.length > 0){
		 arr1[i][0] += searchFilterExist[0][0];
    }
    
    let someIndex = arr2.indexOf(searchFilterExist[0]);
    if(someIndex > -1){
    	arr2.splice(someIndex, 1);
    }   
 
  }
  const answer = arr1.concat(arr2).sort((a, b) => {  		     
 		const descriptionA = a[1].toUpperCase(); // ignore upper and lowercase
  	const descriptionB = b[1].toUpperCase(); // ignore upper and lowercase
  	if (descriptionA < descriptionB) {
    	return -1;
  	}
  	if (descriptionA > descriptionB) {
    	return 1;
  	}
  // names must be equal
  return 0;
      
  });

    return answer;
}

// 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"]
];

//const answer = updateInventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]);
const answer = updateInventory(curInv, newInv);
console.log(''+answer);