How can I find match string in array javascript? [duplicate] - javascript

This question already has answers here:
How do you search an array for a substring match?
(15 answers)
Javascript Searching Array for partial string
(2 answers)
Check for Partial Match in an Array
(5 answers)
Closed 3 years ago.
How can I find a match in an array of strings using Javascript? For example:
var str = "https://exmaple.com/u/xxxx?xx=x";
var filter = ["/u","/p"];
if (!str.includes(filter)){
return 1;
}
In the above code I want to search for var str if match this two values of array filter

This should work:
var str = "https://exmaple.com/u/xxxx?xx=x";
var filters = ["/u","/p"];
for (const filter of filters) {
if (str.includes(filter)) {
console.log('matching filter:', filter);
break; // return 1; if needed
}
}

In your array you need to find the element which includes "/u". filter will return an array and will contain only those element which includes u
var x = ["https://exmaple.com/u/xxxx?xx=x", "https://exmaple.com/p/xxxx?xx=x"];
let matched = x.filter(item => item.includes("/u"));
console.log(matched)

Try this:
var x = ["https://exmaple.com/u/xxxx?xx=x","https://exmaple.com/p/xxxx?xx=x"], i;
for (i = 0; i < x.length; i++) {
if(x[i].includes('/u')) {
document.write(x[i]);
}
}
This loops through all the URLs and picks the one that has /u in it. Then it just prints that out.

Related

How set up an JavaScript Array Object with a length of 5 to display empty strings on each key-value pair [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Is it possible to add dynamically named properties to JavaScript object?
(20 answers)
Closed 2 years ago.
I'm trying to find out how to initialise an array of objects, where each object has the index (i) as its key and 0 as its value. The code below is not working as expected but I can't see why. I'm still quite beginner with Javascript and couldn't find an answer elsewhere.
var n = 10;
var sample = [];
for (var i = 0; i < n; i++)
sample.push({i : 0});
you should use this syntax sample.push({[i]: 0});
when you need to access object property which is stored under some variable you should always use square brackets no matter you need write to or read from an object
The code below should take care of the job:
let n = 10;
let sample = Array.from({length:n}, (_, i) => ({ [i]: 0 }));
As pointed by Oleksandr Sakun on his answer, the index is used between brackets in order to evaluate the variable and set as a property of the object.
For a funcitonal approach you can try:
const initArray = (n)=>{
const newArr = new Array(n).fill(0);
return newArr.map((value, index)=> ({[index]: value}))
}
add square brackets to the index [i] :
var n = 10;
var sample = [];
for (var i = 0; i < n; i++)
sample.push({[i]: 0});
console.log(sample);

find first number in array by js [duplicate]

This question already has answers here:
How to find the array index with a value?
(12 answers)
Find first non-zero value index in an array
(1 answer)
How to find first element of array matching a boolean condition in JavaScript?
(14 answers)
Closed 6 months ago.
I have some arrays as below and I want to know how to get the index of the first number by js?
Arr1=[null,null,null,null,null,...,343,959,543,..,252,null,null,...,null]
You can use findIndex:
Arr1.findIndex(value => value !== null)
You can loop through the array and check it's value:
const Arr1=[null,null,null,null,null,343,959,543,252,null,null,null];
let index = -1;
for(let i = 0; i < Arr1.length; i++)
{
if (Arr1[i] !== null)
{
index = i;
break;
}
}
console.log(index);

Find partial string in array [duplicate]

This question already has answers here:
How do you search an array for a substring match?
(15 answers)
Closed 3 years ago.
var fruits = ["CarPaint.InString.Banana", "CarPaint.InString.Orange", "CarPaint.InString.Apple", "CarPaint.InString.Mango"];
var n = fruits.includes("Mango");
Let's say you don't know whats inside the fruits array ?
How do you extract the string that contains mango.
The prefix string must be included in the result.
Can this be done without a for loop and parsing ?
var fruits = ["CarPaint.InString.Banana", "CarPaint.InString.Orange", "CarPaint.InString.Apple", "CarPaint.InString.Mango"];
var n = fruits.includes("Mango");
console.log(n)
You need to filter the array and check each string.
var fruits = ["CarPaint.InString.Banana", "CarPaint.InString.Orange", "CarPaint.InString.Apple", "CarPaint.InString.Mango"],
result = fruits.filter(string => string.includes("Mango"));
console.log(result);
How about the following?
fruits.filter(fruit => fruit.includes('Mango'))
// [ 'CarPaint.InString.Mango' ]

random and different values when using the Array function “fill” [duplicate]

This question already has answers here:
Creating array of length n with random numbers in JavaScript
(6 answers)
Closed 5 years ago.
const array = new Array(10);
array.fill('hi');
console.log(array);
Using Array::fill to populate a value on the whole array or part of the array.
I have a string generator function that generates a random string.
const getString = () => Math.random().toString(36).replace(/[^a-z]+/g, '');
console.log(getString())
console.log(getString())
console.log(getString())
I want to fill the array with different values by executing the string generator function each time .
It cannot done by one line in fill , however, I found a workaround leveraging the signature of fill : arr.fill(value[, start = 0[, end = this.length]])
const getString = () => Math.random().toString(36).replace(/[^a-z]+/g, '');
const array = new Array(10);
for (var i=0; i < array.length;i++ ) {
array.fill(getString(), i, i + 1);
}
console.log(array);
Does fill supports callbacks that can be executed each iteration to generate different values ?
If no, what is the alternative ?
We can reach the same result in one line combining map and fill :
array.fill().map(getString)
const getString = () => Math.random().toString(36).replace(/[^a-z]+/g, '');
const array = new Array(10);
console.log(array.fill().map(getString))

Dynamically create js Array filled with certain value [duplicate]

This question already has answers here:
Create an array with same element repeated multiple times
(25 answers)
Closed 7 years ago.
I'm wondering if there is a way to create javascript/jquery array in one-liner to receive something like:
my_array = ['-', '-', ,'-' ,'-']
Idea is that array should be created with dynamic length and all values filled with given value.
Thanks in advance!
Try:
var total = 4;
var my_array = new Array(total + 1).join("-").split("");
document.write(JSON.stringify(my_array))
.fill Support The native function will be added in (ECMAScript 6), but for now is not available.
if(!Array.prototype.fill){
Array.prototype.fill = function(val){
for (var i = 0; i < this.length; i++){
this[i] = val
}
return this
}
}
var my_array = new Array(4).fill("-"); //returns ["-","-","-","-"]
Try to use:
Array.apply(null, new Array(63)).map(String.prototype.valueOf,"-")

Categories

Resources