Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I use includes() function on nested arrays?

I have an array like this:

var arr = [];
arr = [['red', 685], ['green', 210], ['blue', 65]];

Also I have two variables:

var color  = 'blue';
var number = 21;

All I'm trying to do is checking the first item of each nested array of arr and then either update the second item of it or make a new array for it.

Here is some examples:

Input:

var color  = 'blue';
var number = 21;

Expected output:

arr = [['red', 685], ['green', 210], ['blue', 21]];

Input:

var color  = 'yellow';
var number = 245;

Expected output:

arr = [['red', 685], ['green', 210], ['blue', 21], ['yellow', 245]];

Here is what I've tried so far:

if ( !arr.includes(color) ) {
    arr.push([color, number]);
} else {
    arr[color] = time;
}

But !arr.includes(color) condition is wrong. Because each item of arr is also an array. Anyway, how can I use includes() function on the first item of nested arrays?

like image 348
stack Avatar asked Apr 20 '17 06:04

stack


2 Answers

You cannot directly use includes on nested array, however, you can use find on array.

arr.find(el => el[0] === color)

This will return the element of array found else undefined. The returned value can be used to update the second element in the array.

var arr = [
  ['red', 685],
  ['green', 210],
  ['blue', 65]
];
var color = 'blue';
var number = 21;


function upsert(array, color, number) {
  var exists = arr.find(el => el[0] === color);

  if (exists) {
    exists[1] = number;
  } else {
    arr.push([color, number]);
  }
}

upsert(arr, color, number);
console.log(arr);


var color = 'yellow';
var number = 245;
upsert(arr, color, number);
console.log(arr);
like image 135
Tushar Avatar answered Oct 21 '22 20:10

Tushar


Simply iterate the array and update the value if found, else push a new value

Demo

var arr = [['red', 685], ['green', 210], ['blue', 65]];
console.log(updateArray(arr, 'blue', 21));

function updateArray(arr, color, value)
{
  var isFound = false;
  arr = arr.map( function(item){
     if( item[0] == color )
     {
       isFound = true;
       item[1] = value;
     }
     return item;
  });
  if ( !isFound )
  {
    arr.push([color, value]);
  }
  return arr;
}
like image 23
gurvinder372 Avatar answered Oct 21 '22 19:10

gurvinder372