I'm bashing my head over this one. I have tried using indexOf() and made my own function to iterate through the array and compare each term but I am always getting -1!
function checkindex(array,temp) {
for(var i = 0; i < array.length; i++) {
console.log(array[i] + " " + temp);
if (array[i] == temp) return i;
}
return -1;
}
array is an Object which is generated this way:
var array = (req.body.somestring).split(',');
When I output array and string this way:
console.log(array[i] + " " + temp);
I get something like this:
["My variable","Something else"] My variable
The spelling matches but its still -1. array.indexOf(temp) gives me the same results. Any thoughts?
Thanks in advance.
This seems to work for me:
var array = ["My variable","Something else"];
var lookup = "My variable";
var index = array.indexOf(lookup);
alert(index);
There is a nice polyfill for older browsers that can be found here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
So the problem was actually more upstream... I stringified the data (JSON.stringify) prior to sending it so the string from var array = (req.body.somestring).split(','); included brackets and all. That why the output of console.log(array) looked like this:
["My variable","Something else"]
The elements in this situation are:
array[0] === ["My variable"
array[1] === "Something else"]
The solution was instead of split was use JSON.parse. The output of console.log(array) after that was:
My variable,Something else
Thank you for your help.
Related
As far as I know, you can only save strings to local storage. So, I had to write a function so that I could save arrays. If I call console.log(fixA(["string1", [5, [false]], "string2"])); I get an output of "'string1',[5,[false]],'string2'". Here it is:
function fixA(array) {
var toreturn = "";
for (var i = 0; i < array.length; i++) {
if (typeof array[i] === 'object') {
toreturn += "[" + fixA(array[i]) + "]";
} else {
if (typeof array[i] === 'string') {
toreturn += "'" + array[i] + "'";
} else {
toreturn += array[i];
}
}
if (i < array.length - 1) {
toreturn += ",";
}
}
return toreturn;
}
console.log(fixA(["string1", [5, [false]], "string2"]));
The issue now is that I have no clue how to convert it back. I've tried a few things but have always gotten stuck on how I convert the arrays back. This is basically what I've tried:
function fixS(string) {
var toreturn = [];
var temp = string.split(",");
for (var i = 0; i < temp.length; i++) {
// I could run a check here to see if temp[i] starts with "[", but I'm not sure how to tell where the array ends.
// If it is an array, then I'd need to pass everything inside of the array back into fixS, making it recursive.
// The times I tried to do those two things above, I ran into the issue that the commas inside of the sub arrays also split everything, which I don't want (as the recursive function will deal with that).
toreturn.push(temp[i]);
}
return toreturn;
}
console.log(fixS("'string1',[5,[false]],'string2'"));
// This also doesn't return numbers as numbers or booleans as booleans.
Not much there, but it's as far as I've gotten. Any help is appreciated.
Instead of doing your own bespoke solution, unless you have something that can't be represented in JSON (your example can be), use JSON:
On page load:
var data = JSON.parse(localStorage.getItem("data") || "null");
if (!data) {
// There wasn't any, initialize
}
or
var data = JSON.parse(localStorage.getItem("data") || "{}");
...if you want a blank object if there is nothing in local storage.
When saving your data:
localStorage.setItem("data", JSON.stringify(data));
As David said there's JSON.stringify() & JSON.parse();
you can use those methods :
function save_to_storage(id, anything){
localStorage.setItem(id, JSON.stringify(anything));
}
function load_from_storage(id){
return JSON.parse(localStorage.getItem(id));
}
It can be achieved with help of JSON.stringify and JSON.parse functions.
Let me explore with help of code snippet.
var original_arr = ["string1", [5, [false]], "string2"]; // array
// Converting this array into string
var converted_str = JSON.stringify(original_arr); // converted into string
// Converting this string back to array
var new_arr = JSON.parse(converted_str ); // back to array
The other answers have already covered it, but note that P5.js also provides functionality for working, saving, and loading JSON directly.
Take a look at the saveJSON() and loadJSON() functions in the reference.
Write a function called indexToString. This function should:
1. Take an array as an argument
2. Create and return a new array of all passed array elements as strings
3. Each strings should be formatted like so: “[index] is [element at index]”
This is the error I am getting: returns an array of passed-in array elements as strings with element index specified
expected undefined to deeply equal [ '0 is 1', '1 is 2', '2 is 3' ]
Here is my code:
var indexToString = function(array){
index = 0;
elementAtIndex = 0;
var i = 0;
while(i < array.length){
console.log(index + " is " + elementAtIndex);
i++
}
return array[i];
};
Two Three errors.
Firstly, the while loop will exit when i is no longer less than array.length; the first such number is array.length. This means, at the end of the loop, array[i] is array[array.length], which is just outside the array, thus undefined.
Secondly, you are supposed to return an array of strings, as told by your test failure message; not print them to the console.
EDIT: Thirdly, what Spencer said. :) Use i instead of index, and array[i] instead of elementAtIndex.
You want to start with an empty array outside the loop, and push each string you construct into it; then return that array after the loop.
Or you can do it with "new" JavaScript:
var indexToString = array => array.map((e, i) => `${i} is ${e}`)
You should reflect a bit more on your code, it is quite nonsense so far.
Let's decompose the question to identify what should be done:
Write a function called indexToString. This function should:
Take an array as an argument
Create and return a new array of all passed array elements as strings
Each strings should be formatted like so: “[index] is [element at index]”
So:
you create a function called indexToString which body contains the code, as you did.
In the initialization part before your while, you should create a new empty array that is going to be filled, and declare an integer called index for example initialized at 0 that is going to be used to loop through the original array. (Tip: var new_array = []; to create, and use new_array.push(elem); to append an element)
in your while, you should push at the end of your new array a string built as follow: "["+index+"] is ["+array[index]+"]" AND you should increment your index. You loop while(index < array.length).
At the end, you can return the new array !
Good luck with learning programming!
If the arraylenth is 10, the function will return array[10].This is an array-bound.
When you enter the last loop, the i becomes equal to array.length, so array[i] is undefined after this. But probably this is not what you wanted. you want to return the full array.
var indexToString = function(array){
var new_array = [];
var i = 0;
while(i < array.length){
new_array[i] = i + " is " + array[i];
i++;
}
return new_array;
};
console.log(indexToString([1,2,3]));
I am getting an output which looks like this
var x = ["title: x_one", " description: 1", " value: 4"]
where x[0] returns title: x_one
Which is a string. I cant read the property of title. How would I convert it into an object so that eventually I will be able to loop through the array and read the properties such as title, description and value.
I am trying to do this through jquery
I have been looking for a solution but havent really found one. If there is any out there which I am missing I would highly appreciate if anyone else have and could point me to that
Loop through your array, splitting the values at the : character. Then use the first part as a property name, the second part as the value, in an object.
var obj = {};
for (var i = 0; i < x.length; i++) {
var split = x[i].split(':');
obj[split[0].trim()] = split[1].trim();
}
Try this function I have already tested it
var a=new Array();
for(var i=0;i<x.length;i++){
var tmp=x[i].split(":")
a[tmp[0]]=tmp[1]
}
A more up to date version that that uses some newer language
const splitStr = (x) => {
const y = x.split(':');
return {[y[0].trim()]: y[1].trim()};
}
const objects = ["title: x_one", " description: 1", " value: 4"].map(splitStr)
console.log(objects)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
http://www.ecma-international.org/ecma-262/6.0/#sec-object-initializer
Assuming you have an object before you create this array you don't need to convert this to anything. Using jQuery's each you can get the value and the key.
$.each( obj, function( key, value ) {
alert( key + ": " + value );
});
If this is the final output then you can just use String.prototype.split when you loop through.
Just bumped into this. Here is another solution for OP's original array.
var x = ["title: x_one", " description: 1", " value: 4"]
function mapper(str)
{
var o = {};
strArr = str.split(":");
o[strArr[0].trim()] = strArr[1].trim();
return o;
}
var resultArray = x.map(mapper);
console.log(resultArray[0].title);
console.log(resultArray[1].description);
console.log(resultArray[2].value);
fiddle
I have produced an array using:
var arr = [];
arr = string.match(/(?:^| )([a-z]+)(?= [A-Z])/g);
This works as expected and the array is full and can be seen using
console.log or alert().
The array consists of words which I need to filter, so I am trying to
use .splice to remove unwanted instances of the same word using:
for (var i = arr.length - 1; i >= 0; i--) {
if (arr[i] === 'jim') {
arr.splice(i, 1);
}
}
The for loop doesn't recognize any instances of, for instance, 'jim' in
the array although there are several.
I tried the loop using an array I made myself and it worked fine, ie:
arr = ['jim', 'bob', 'arthur', 'jim', 'fred']
I have also tried the following which reports that 'jim' !== 'jim' as well as the other names not equalling 'jim'. Again this loop works fine with the self assigned array.
var i = arr.length;
while ( i-- )
if (arr[i] === 'jim')
arr.splice(i, 1);
else
alert( "'" + arr[i].toString() + "' !== 'jim'" );
What is it about the array produced by the string.match that I am not
understanding? Any help would be much appreciated.
You can save a lot of time by using Array.filter():
arr = arr.filter(function(x){
return x.trim() !== 'jim';
});
James is right: whitespace charcters cause the problem here.
When I try your examples above the test alerts:
' jim' !== 'jim'.
The first part/bracket of your regEx includes a whitespace character in the matched strings.
The generated array will most likely be something like: arr = [' jim', ' bob', ' arthur', ' jim', ' fred'].
I'm working on a program that extract information from a large chuck of text using javascript and while looking at a former co-workers code of something similar I found that when you save the result of .exec() and do .index of that variable it gives you the index of that substring in the array.
Example:
var str="I found this for you!";
var pattern=/this/igm;
var result=pattern.exec(str);
document.write("\"This\" Index = " + result.index + ".");
Result:
"This" Index = 8.
When I looked online I found that exec() returns an array and it looks like arrays don't have an .index property. All my searches of .index seem to come up index().
What is going on here? Why does this work? I'm also wondering if there are some other things I can do related to this (like .lastindex).
Here is a great resource on what exec does. It not only returns an array with extra properties like index, but it also modifies the regex object that was used.
Try this:
var str="I found this for you!";
var pattern=/this/igm;
var result=pattern.exec(str);
for(var i in result){
console.log("i: " + i);
console.log("result[" + i + "]: " + result[i]);
}
// i: 0
// result[0]: this
// i: index
// result[index]: 8
// i: input
// result[input]: I found this for you!
index is a special property added to the array by exec. It does not necessarily have to be there by default, and reproducing the behaviour yourself is quite easy.
var example = [1, 2, 3];
example.index = 15;