How can I use the 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 am trying to do is check the first element of each nested array arr
and then either update the second element or create a new array for it.
Here are some examples:
Input:
var color = 'blue';
var number = 21;
Expected Result:
arr = [['red', 685], ['green', 210], ['blue', 21]];
Input:
var color = 'yellow';
var number = 245;
Expected Result:
arr = [['red', 685], ['green', 210], ['blue', 21], ['yellow', 245]];
Here's what I've tried so far:
if ( !arr.includes(color) ) {
arr.push([color, number]);
} else {
arr[color] = time;
}
But the condition !arr.includes(color)
is wrong. Since each element is arr
also an array. Anyway, how can I use the function includes()
for the first element of nested arrays?
source to share
You cannot directly use includes
on a nested array, however you can use find
on an array.
arr.find(el => el[0] === color)
This will return the element of the found array else undefined
. The return 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);
source to share
Just iterate through the array and update the value if found, otherwise push the 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;
}
source to share
You must make a loop that loops through the array because, as you pointed out yourself, each element of the array is itself an array.
If you do:
for(let i = 0; i < arr.length; i++){
if ( !arr[i].includes(color) ) {
arr.push([color, number]);
} else {
arr[i][1] = time;
}
}
This way you check if the array at position has a i
color unless you push the new array into the array, otherwise you will change the value of the array at index 1 of the arrayi
source to share