RoboPHP
RoboPHP

Reputation: 420

Searching For Existing Values in Array

I have been trying to search for an existing value in an array like below

var values = []
values.push(localStorage.getItem('items'));

console.log(values);

if (values.includes(2)) {
  alert('Already Exists.');
}

When i console the array values i have output as ["1,2,3,4,5,6"] so the code treats the array as having just one index which is index[0] which makes the search quite challenging for me.

My challenge is how to find the value 2 in the array values ?

Upvotes: 0

Views: 51

Answers (4)

Curtis Crentsil
Curtis Crentsil

Reputation: 501

firstly get the values from local storage store it in a variable, split it using the split function, then check if the number is inside the array, alert the message if it returns true

var values  =localStorage.getItem('items')
    var spliter = values.split(',')
    console.log(spliter);

    if (spliter.includes('2') == true) {
      alert('Already Exists.');
    }

Upvotes: 0

Emilis Kiškis
Emilis Kiškis

Reputation: 25

First of all, this isn't jQuery, it's vanilla JS.

Second, after doing localStorage.setItem("items", [1,2,3,4,5,6]);, items in local storage will equal to "1,2,3,4,5,6", which is no longer the appropriate format.

Rather, save your array with localStorage.setItem("items", JSON.stringify([1,2,3,4,5,6]));. When you want to retrieve those items, write let vals = JSON.parse(localStorage.getItem("items"));, and search in vals with

  • vals.includes(2) for a true/false answer,
  • vals.find(val => val === 2) for 2 or undefined,
  • val.indexOf(2) to get the index of the first element equal to 2.

Hope this helps.

Upvotes: 0

vadivel a
vadivel a

Reputation: 1794

Hope this help you.

    var names_arr = '["1,2,3,4,5,6"]'; 
names_arr = names_arr.replace("'",'');
 
function checkValue(value,arr){
  var status = 'Not exist';
 
  for(var i=0; i<arr.length; i++){
    var name = arr[i];
    if(name == value){
      status = 'Exist';
      break;
    }
  }

  return status;
}
console.log('status : ' + checkValue('3', names_arr) );
console.log('status : ' + checkValue('10', names_arr) );

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337580

localStorage can only hold strings. As such you need to convert the value you retrieve in to an array, which can be done using split().

Also note that the resulting array will contain string values, so you need to use includes('2'). Try this:

var values = "1,2,3".split(','); // just for this demo
//var values = localStorage.getItem('items').split(',');
console.log(values);

if (values.includes("2")) {
  console.log('Already Exists.');
}

Upvotes: 2

Related Questions