I have an array of names from A-Z in ABC order and I want to get all the names from A to J. Is there any way to do this besides checking the first letter of each character against an array of all the letters from A to J?
Example:
var array=['Amy','Dolly','Jason','Madison','Patricia'];
And I want an array of Amy, Dolly and Jason.
You can use filter function like
var array=['Amy','Dolly','Jason','Madison','Patricia'];
var filtered = array.filter(function(el){return el[0]>='A' && el[0]<='J'})
var array=['Amy','Dolly','Jason','Madison','Patricia'];
var filtered = array.filter(function(el){return el[0]>='A' && el[0]<='J'});
document.getElementById('res').innerHTML = JSON.stringify(array) + '<br />' + JSON.stringify(filtered);
<div id="res"></div>
Code above checking all element in array, if you want avoid it and array already sorted, you can use simple for loop
var array=['Amy','Dolly','Jason','Madison','Patricia'];
var result=[];
for(var i=0;i<len=array.length; i<len && (array[i][0]>='A' && array[i][0]<='J'); i++){
result.push(array[i]);
}
or same in one liner
for(var i=0, result=[], len=array.length; i<len && (array[i][0]>='A' && array[i][0]<='J');result.push(array[i]),i++);
in result - filtered collection;
Yet another way find index and then use slice like
for(var i=0, len=array.length; i<len && (array[i][0]>='A' && array[i][0]<='J');i++);
var result = array.slice(0,i);
Interesing way from #dandavis in comment with filter and regex
var filtered = array.filter(/./.test, /^[A-J]/);
it altervative for
var regex = /^[A-J]/;
var filtered = array.filter(function(el){ return regex.test(el); });
You can do this using regular expression..
var array=['Amy','Dolly','Jason','Madison','Patricia'];
var reg = new RegExp('^[A-J]');
var arrTemp=[];
var intLength = array.length;
for(var i=0;i<intLength ;i++){
if(reg.test(array[i])) {
arrTemp.push(array[i])
}
}
console.log(arrTemp)
If you want consider case-sesitive nature then you can write your regular expression like
var reg = new RegExp('^[A-Ja-j]');
You can use the ascii-value of the character and use a filter to get the result you want. The character code value of "J" is 74 and for "A" it is 65.
array.filter(function(v) { return v.charCodeAt(0) >= 65 && v.charCodeAt(0) <= 74 })
var array = ['Amy', 'Dolly', 'Jason', 'Madison', 'Patricia'],
bound = { lower: 'A', upper: 'J' },
newArray = [],
i = 0, j, l = array.length;
// lookup for the first element of the array which is smaller than the lower bound
while (i < l && array[i][0] < bound.lower) {
i++;
}
j = i;
// lookup for the end of the upper bound and skip the rest
while (j < l && array[j][0] <= bound.upper) {
j++;
}
// build new array
newArray = array.slice(i, j);
Related
I have an array that I want to check, for example:
var str = ["a","b","c","d","e","f"];
but I want check if this array's string values are in a database or of some sort. I want to find out which one matches and store the found matches inside an array.
var dataFound = [];
var count = 0;
for(var stringData in someDatabase){
if(stringData == str[0] || stringData == str[1] ...etc){
dataFound[count] = stringData;
count++;
}
}
//someDatabase will consist of strings like random alphabets
from a-z
I don't want to hardcode the if-statement because a query array can be anywhere from a, b, c .. (n) as n can represent any amount of strings. I tried to use a for-loop from 0 to str.length but that can take quite a while when I can use or operator to search in one go with all the string values, is there a way around this?
if (str.indexOf(stringData) > -1) {
//found
}
Array.prototype.indexOf() (MDN)
If str is an array, can you do this?
var dataFound = [];
var count = 0;
for(var stringData in someDatabase){
for (i++; i < str.length; i++) {
if(stringData == str[i]){
dataFound[count] = stringData;
count++;
}
}
}
I am checking that a particular value of an array is exist in a string or not. For that I had implemented the following code
function Check() {
var Value = 'I III';
var Opt = new Array("I", "II", "III", "IV");
for (var i = 0; i < Opt.length; i++) {
if (Value.indexOf(Opt[i]) > -1) {
alert("Hello");
}
}
}
if value exists in string it should display an alert, but the problem is that it display the alert 3 times instead of 2 times, because indexOf is assuming II as a part of string because III exists in string.
The easiest way to work around this would be to split Value with a delimiter (e.g., at each space) with String.prototype.split:
var value = 'I III'.split(' ')
var options = ['I', 'II', 'III', 'IV']
options.forEach(function(option) {
var index = value.indexOf(option)
if (index !== -1) {
// don't use `document.write` in general; it's just very useful in stack snippets
document.write(index + ' : ' + value[index])
document.write('<br>')
}
})
A couple notes:
don't capitalize your variable names; use camelCase for variables and PascalCase for classes/etc
don't use new Array(); instead prefer the array literal: []
This is the another way to get the ans
function Check() {
var Value = 'I III'.split(" "); var Opt = ["I", "II", "III", "IV"];
for (var i = 0; i < Opt.length; i++) {
if (Value.indexOf(Opt[i]) > -1) {
alert("Hello");
}
}
}Check();
I have a strings that can look like this:
left 10 top 50
How can i extract the numbers, while the numbers can range from 0 to 100 and words can be left/right top/bottom? Thanks
Try match()
var text = "top 50 right 100 left 33";
var arr = text.match(/[0-9]{1,3}/g);
console.log(arr); //Returns an array with "50", "100", "33"
You can also use [\d+] (digits) instead of [0-9]
Place this string in a var, if you know every number will be seperated by a space you can easely do the following:
var string = "top 50 left 100";
// split at the empty space
string.split(" ");
var numbers = new Array();
// run through the array
for(var i = 0; i < string.length; i++){
// check if the string is a number
if(parseInt(string[i], 10)){
// add the number to the results
numbers.push(string[i]);
}
}
Now you can wrap the whole bit in a function to run it at any time you want:
function extractNumbers(string){
var temp = string.split(" ");
var numbers = new Array();
for(var i = 0; i < temp.length; i++){
if(parseInt(temp[i], 10)){
numbers.push(temp[i]);
}
}
return numbers;
}
var myNumbers = extractNumbers("top 50 left 100");
Update
After reading #AmirPopovich s answer, it helped me to improve it a bit more:
if(!isNaN(Number(string[i]))){
numbers.push(Number(string[i]));
}
This will return any type of number, not just Integers. Then you could technically extend the string prototype to extract numbers from any string:
String.prototype.extractNumbers = function(){ /*The rest of the function body here, replacing the keyword 'string' with 'this' */ };
Now you can do var result = "top 50 right 100".extractNumbers();
Split and extract the 2nd and 4th tokens:
var arr = "left 10 top 50".split(" ");
var a = +arr[1];
var b = +arr[3];
var str = 'left 10 top 50';
var splitted = str.split(' ');
var arr = [];
for(var i = 0 ; i < splitted.length ; i++)
{
var num = Number(splitted[i]);
if(!isNaN(num) && num >= 0 && num <= 100){
arr.push(num);
}
}
console.log(arr);
JSFIDDLE
If you want it dynamically by different keywords try something like this:
var testString = "left 10 top 50";
var result = getNumber("top", testString);
function getNumber(keyword, testString) {
var tmpString = testString;
var tmpKeyword = keyword;
tmpString = tmpString.split(tmpKeyword + " ");
tmpString = tmpString[1].split(' ')[0];
return tmpString;
}
var myArray = "left 10 top 50".split(" ");
var numbers;
for ( var index = 0; index < myArray.length; index++ ) {
if ( !isNaN(myArray[index]))
numbers= myArray[index]
}
find working example on the link below
http://jsfiddle.net/shouvik1990/cnrbv485/
In my javascript, I've an array named my_array holding values like 0121, 1201, 0012, 0202 etc.
Each individual digit in the string is of importance. So, in the above example, there are 4 values in one string. E.g. 0121 holds 0,1,2,1.
The values can also be longer too. E.g. 01221, 21021 etc. (This is holding 5 values)
I want to know of the easiest and most effective way to do the following:
Add the first digits of all the strings in the array my_array. E.g. 0+1+0+0 in the above example
Add the second digits (e.g. 1+2+0+2) and so on.
I can loop through the array and split the values, then
for(i=0; i<my_array.length; i++){
var another_array = my_array[i].split();
//Getting too complicated?
}
How can I do it effectively? Someone please guide me.
Something like this
var myArray = ["0121", "1201", "0012", "0202"];
var firstValSum = 0;
for(var i = 0; i < myArray.length; i++) {
var firstVal = myArray[i].split("");
firstValSum += parseInt(firstVal[0], 10);
}
console.log(firstValSum); //1
This could be wrapped into a function which takes parameters to make it dynamic. i.e pass in the array and which part of the string you want to add together.
EDIT - This is a neater way of achieving what you want - this code outputs the computed values in an array as you specified.
var myArray = ["0121", "1201", "0012", "0202"];
var newArr = [];
for(var i = 0; i < myArray.length; i++) {
var vals = myArray[i].split("");
for(var x = 0; x < vals.length; x++) {
var thisVal = parseInt(vals[x], 10);
( newArr[x] !== undefined ) ? newArr[x] = newArr[x] += thisVal : newArr.push(thisVal);
}
}
console.log(newArr); //[1, 5, 3, 6];
Fiddle here
var resultArray = new Array(); // This array will contain the sum.
var lengthEachString = my_array[0].length;
for(j=0; j<lengthEachString ; j++){ // if each element contains 4 elements then loop for 4 times.
for(i=0; i<my_array.length; i++){ // loop through each element and add the respective position digit.
var resultArray[j] = parseInt( my_array[i].charAt(j) ); // charAt function is used to get the nth position digit.
}
}
I've got a string!
7 serpents
4 bikes
2 mangoes
It's made up of number + [space] + thing-string. I need to be able to order the whole string with reference to the number. So it should come out:
2 mangoes
4 bikes
7 serpents
It's a simple bubble sort for the number and then cross-referencing the index to get the final order. The JavaScript code below works, but I can't help but think it could be made more efficient. Am I missing a trick here??
And remember: I'm an artist, so I code in crayon!
var eventsStr = "7 serpents\n4 bikes\n2 mangoes"
var splitArr = eventsStr.split("\n")
var numArray = new Array();
var events = new Array();
for (var i = 0; i < splitArr.length; i++)
{
var temp = splitArr[i] ;
var part1 = temp.substring(0, temp.indexOf(" "))
var part2 = temp.substring(temp.indexOf(" ")+1, temp.length)
numArray[i] = part1;
events[i] = part2;
}
var sorted = superCopy(numArray);
var sorted = sorted.sort(sortArrayNumerically);
alert(getOrder(sorted, numArray, events))
function getOrder(orderedarr, arr1, arr2)
{
var str = "";
for (var i = 0; i < arr1.length; i++)
{
for (var j = 0; j < orderedarr.length; j++)
{
if (arr1[i] == orderedarr[j])
{
// found the thing !what is the event?
str += arr1[i] + " " + arr2[i] + "\n";
}
}
}
return str
}
function sortArrayNumerically(a,b)
{
return a - b;
}
function superCopy(arr)
{
tempArr = new Array();
for (var i = 0; i < arr.length; i++)
{
tempArr[i] = arr[i]
}
return tempArr
}
You could use JavaScript's sort() function:
eventsStr.split('\n').sort().join('\n');
eventsStr.split('\n') - first split the string on the newline character to create an array
.sort() - then use the sort() function to sort the array
.join('\n') - then put the string back together, joining the array elements with a newline between them
Reference:
String.prototype.split()
Array.prototype.sort()
Array.prototype.join()
This is an alphabetic sort though, so if your string contained, say, 12 mangoes, the result would not be sorted numerically. To sort numerically, you could do something like this:
eventsStr.split('\n').sort(function(a, b) {
return parseInt(a.split(' ')[0], 10) > parseInt(b.split(' ')[0], 10);
}).join('\n');
In this situation, the sort() function is called with a callback parameter, taking 2 values: the first string to be compared and the second string to be compared. This callback function then splits the string, extracts the number and compares it with the number in the other string.
Use
splitArr.sort() // as per your code
DEMO
var eventsStr = "7 serpents\n4 bikes\n2 mangoes"
arr = eventsStr.split('\n')
# ["7 serpents", "4 bikes", "2 mangoes"]
arr
# ["7 serpents", "4 bikes", "2 mangoes"]
arr.sort()
# ["2 mangoes", "4 bikes", "7 serpents"]