How can I compare a String that comes from HTML, with an array and get the position of it?
var fruit = ["apple", "banana"];
var $textOfHtml = "apple";
The problem is how do I get something like this below:
"apple" is on the [0] position?
Thanks guys.
As the comments suggest, you want to use indexOf.
Using your code, here is the usage:
var fruit = ["apple","banana"]
var $textOfHtml = "apple"
var i = fruit.indexOf($textOfHtml)
var str = $textOfHtml + ' is on the [' + i + '] position'
var fruit = ["apple", "banana"]
var text = "apple"
function compare(array, string, index) {
var x = []
var y = array[index]
x.push(y)
var z = x.toString().trim()
if (z == string) {
return (string + ' is on the ' + index + ' position!')
}
}
.push into an empty array to isolate the array item to run .toString() and then .trim() for good measure does the trick every time
You have to use array indexOf() method to find the positon of your desired value
<body>
<script>
var array = ["apple","banana"];
var text = "banana";
var position = array.indexOf(text);
alert(position);
</script>
</body>
The indexOf() method searches the array for the specified item, and returns its position.
var Index = fruit .indexOf($textOfHtml);
alert($textOfHtml+" is on the ["+Index +"] position");
Related
Let's illustrate my question with some code to make you understand what I need.
I searched for a solution and they always propose to add the element of an array in another array. This is not what I want.
Example:
<script type="text/javascript">
var array_1 = [];
var array_2 = [1,2,3];
var array_3 = [4,5,6];
array_1.push(array_2);
array_1.push(array_3);
alert(array_1);
</script>
This will show :
1,2,3,4,5,6
I would like to get
[1,2,3],[4,5,6]
which means array_1 contains 2 elements : array_2 and array_3
I need that because I will loop array_1 which will print in the HTML the 3 elements of each array (array_2 and array3).
For example:
var main_array = [];
var title_1 = ["My title 1",16,"color:#000;"];
var title_2 = ["My title 2",14,"color:#333;"];
main_array.push(title_1);
main_array.push(title_2);
txt=""
main_array.forEach(myFunction);
document.getElementById("demo").innerHTML = txt;
function myFunction(value, index, array) {
txt = txt + '<span style=\'font-size:' + value[1] + 'color:' + value[2] + '\'>' + value[0] + '</span><br>';
}
I am showing this last example in case it doesn't exist the possibility to add an array inside an array in Javascript. Maybe someone will think of another solution to accomplish what I need to do.
You do get [[1,2,3],[4,5,6]]. It just doesn't seem like it since alert calls toString, which joins all the elements together with a comma. So, [[1,2,3],[4,5,6]].toString() == [1,2,3].toString() + "," + [4,5,6].toString() which is "1,2,3" + "," + "4,5,6" which is "1,2,3,4,5,6". Just console.log it and you'll see it's a nested array.
const array_1 = [1,2,3];
const array_2 = [4,5,6];
const array_3 = [[...array_1], [...array_2]];
I've created an associative array for index spaces inside a sentence for example:
sentence: hello how are you? (spaces between the word 'hello' to 'how')
so my array looks like this:
indexed_words[0] = hello
indexed_words[0_1] = space
indexed_words[0_2] = space
indexed_words[0_3] = space
indexed_words[0_4] = space
indexed_words[0_5] = space
indexed_words[0_6] = space
indexed_words[0_7] = space
indexed_words[1] = how
indexed_words[2] = are
indexed_words[3] = you?
but when I use 'for' loop its show me (using alert) the indexes 0,1,2,3 first and after them the sub-indexes, its mixed up my array order, any idea?
here my code:
function words_indexer(user_content)
{
var words_array = user_content.split(" ");
var indexed_words = {};
var word_counter = 0
var last_word_counter = 0
$.each(user_content, function(word_key,word_value){
if(word_value === ''){
var indexed_key = last_word_counter + '_' + word_key;
indexed_words[indexed_key] = word_value;
}else{
var indexed_key = word_counter;
indexed_words[indexed_key] = word_value;
last_word_counter = word_counter;
word_counter++;
}
});
for (var key in indexed_words) {
alert(key + ' ' + indexed_words[key]);
}
}
If your array index needs an extra level of structure then it may be better to just create a nested array instead:
indexed_words[0] = hello
indexed_words[0][1] = space
indexed_words[0][2] = space
indexed_words[0][3] = space
indexed_words[0][4] = space
indexed_words[0][5] = space
indexed_words[0][6] = space
indexed_words[0][7] = space
indexed_words[1] = how
indexed_words[2] = are
indexed_words[3] = you?
I believe adding an underscore to your array key may actually cause Javascript to consider it as being a string which would bump your numeric keys up above it.
You can't use non-numeric indexes for arrays in javascript (a_b is not considered numeric). For this you probably should use an object. And then loop through it like this:
for(var word_key in indexed_words) {
if(!indexed_words.hasOwnProperty(word_key)) continue;
var word_value = indexed_words[word_key];
// Your code
}
I am new for javascript, I have a one long string i want to split after 3rd commas and change diffferent format. If you are not understand my issues. Please see below example
My string:
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
I want output like this:(Each item should be in next line)
Idly(3 Pcs) - 10 = 200
Ghee Podi Idly - 10 = 300
How to change like this using JavaScript?
Just copy and paste it. Function is more dynamic.
Example Data
var testData = "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
Function
function writeData(data){
data = data.split(',');
var tempLine='';
for(var i=0; i<data.length/3; i++) {
tempLine += data[i*3+1] + ' - ' + data[i*3] + ' = ' + data[i*3+2] + '\n';
}
alert(tempLine);
return tempLine;
}
Usage
writeData(testData);
Use split method to transform the string in a array and chunk from lodash or underscore to separate the array in parts of 3.
// A custom chunk method from here -> http://stackoverflow.com/questions/8495687/split-array-into-chunks
Object.defineProperty(Array.prototype, 'chunk_inefficient', {
value: function(chunkSize) {
var array=this;
return [].concat.apply([],
array.map(function(elem,i) {
return i%chunkSize ? [] : [array.slice(i,i+chunkSize)];
})
);
}
});
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
var arr = test.split(',');
var arr = arr.chunk_inefficient(3);
arr.forEach(function (item) {
console.log(item[1]+' - '+item[0]+' = '+item[2]);
});
You can use split to split the string on every comma. The next step is to iterate over the elements, put the current element into a buffer and flush the buffer if it's size is three. So it's something like:
var tokens = test.split(",");
var buffer = [];
for (var i = 0; i < tokens.length; i++) {
buffer.push(tokens[i]);
if (buffer.length==3) {
// process buffer here
buffer = [];
}
}
If you have fix this string you can use it otherwise validate string.
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
var test2= test.split(",");
var temp_Str= test2[1]+' - '+test2[0]+' = '+test2[2]+'\n';
temp_Str+= test2[4]+'-'+test2[3]+' = '+test2[5];
alert(temp_Str);
I have an array. I want to add some characters (:,\n) to each element in that array to be shown in a text box.
Currently this is what I'm doing
$scope.source.arr = .... //This is an array
var actualText = "";
function func() {
$scope.source.arr.forEach(function(ele){
actualText += "***" + ele + " - \n"; //Adding necessary characters
})
}
var showText = function() {
func(); //Calling the function that populates the text as needed
var textBox = {
text : actualText;
...
}
}
Is there a better way to do this?
You can simply use Array.prototype.map to create a new Array object with the changed strings, like this
var textBox = {
text: $scope.source.arr.map(function(ele) {
return "***" + ele + " - ";
}).join("\n"),
...
};
For each element in the arr, we are creating a new string corresponding to it and creating an array of strings. Finally we join all the strings in the array with \n.
You can use Array.prototype.map, Array.prototype.reduce to make it better.
Check reduce function here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
var prefix = "***";
var postfix = "$$$";
var targetStrArr = ["apple", "banana"]
var resultStr = targetStrArr.map(function(ele){
return prefix + ele + postfix; //Adding necessary characters
}).reduce(function(prevVal, curVal) {
return prevVal + curVal;
});
console.log(resultStr); // ***apple$$$***banana$$$
friends.
I have an array and it contains some string values.
ex: array name="All_array"
Now i want to check all values in that array for first character of a string.
if a String starts with character 'a' then move that string to array called "A_array".
if a String starts with character 'b' then move that string to array called "B_array".
How to achieve this task.
var splitArrays = {};
for(var i = 0; i < All_array.length; ++i){
var firstChar = All_array[i].substr(0,1).toUpperCase();
if(!splitArrays[firstChar + '_array'])
splitArrays[firstChar + '_array'] = [];
splitArrays[firstChar + '_array'].push(All_array[i]);
}
This will take every element in All_array and put them into an object containing the arrays indexed by the first letter of the elements in All_array, like this:
splitArrays.A_array = ['Abcd','Anej','Aali']
etc...
Here's a fiddle: http://jsfiddle.net/svjJ9/
The code would be this:
for(var i=0; i<All_array.length; i++){
var firstChar = All_array[i].substr(0, 1).toUpperCase();
var arrayName = firstChar + "_array";
if(typeof(window[arrayName]) == 'undefined') window[arrayName] = []; //Create the var if it doesn't exist
window[arrayName].push(All_array[i]);
}
A_array = []; //empty the array (cause you wanted to 'move')
Hope this helps. Cheers
You could do it using each() and charAt:
$.each(All_array,function(i,s){
var c = s.charAt(0).toUpperCase();
if(!window[c + '_array']) window[c + '_array'] = [];
window[c + '_array'].push(s);
});