Filter array by content? - javascript

I'm trying to filter an array that is non-object based, and I need the filter to simply check each piece of the array for a specific string.
Say I have this array:
["http://mywebsite.com/search", "http://mywebsite.com/search", "http://yourwebsite.com/search"]
What I need to do is harvest the array in a way so that I get a new array that only contain those who start with http://mywebsite.com and not http://yourwebsite.com
In conclusion making this: ["http://mywebsite.com/search", "http://mywebsite.com/search", "http://yourwebsite.com/search"]
into this ["http://mywebsite.com/search", "http://mywebsite.com/search"]

You can filter the array using .filter() and .startsWith() method of String.
As from Docs:
The startsWith() method determines whether a string begins with the characters of a specified string, returning true or false as appropriate.
Demo:
let data = ["http://mywebsite.com/search",
"http://mywebsite.com/search",
"http://yourwebsite.com/search"];
let result = data.filter(s => s.startsWith('http://mywebsite.com/'));
console.log(result);
As mentioned in your comment; if you wants to check multiple strings then you can try this:
let data = ["http://mywebsite.com/search",
"http://mywebsite.com/find",
"http://yourwebsite.com/search",
"http://yourwebsite.com/find"];
let strToMatch = ["http://mywebsite.com/search", "http://mywebsite.com/find"];
let result = data.filter(s1 => strToMatch.some(s2 => s2.startsWith(s1)));
console.log(result);
Docs:
String.prototype.startsWith()
Array.prototype.filter()
Arrow Functions

Use Array filter() method
You can make a simple function and pass that array of string and check what you want in it exist or not
var yourString = ["http://mywebsite.com/search", "http://mywebsite.com/search", "http://yourwebsite.com/search"];
function specificString(yourString ) {
return yourString === "http://mywebsite.com/search";
}
console.log(specificString(yourString));

Related

Javascript: includes return false while matching partial array element

Very simple example here:
var u = []
u.push("https://cloudinary.com/products/media_optimizer/web-performance-guide#get-started")
u.includes("https://cloudinary.com/products/media_optimizer/web-performance-guide") //return false
What am I doing wrong here?
Iterate over the array, checking each element.
const search = (arr, fragment) => arr.some(v => v.includes(fragment));
const u = [
"https://cloudinary.com/products/media_optimizer/web-performance-guide#get-started"
];
const found = search(u, "https://cloudinary.com/products/media_optimizer/web-performance-guide");
console.log(found);
Reference:
.some()
The value you are searching for must be an exact match, and you are not searching for the ending #get-started
You are searching the array for an exact match to your string.
You can use .includes(...) on the string in the array which will return true.
u[0].includes("https://cloudinary.com/products/media_optimizer/web-performance-guide")
your error is to use the includes in an array, the method is for a string value
string.includes(searchvalue, start)
for this to work you need to iterate the array:
u.map(item => item.includes("https://cloudinary.com/products/media_optimizer/web-performance-guide"))

How can i take the objects inside in the array?

I have this Result :
["572a2b2c-e495-4f98-bc0a-59a5617b488c", "2d50c44a-0f94-478b-91b6-bb0cd8287e70"]
But i would like to have only :
"572a2b2c-e495-4f98-bc0a-59a5617b488c", "2d50c44a-0f94-478b-91b6-bb0cd8287e70"
Is this Possible ?
I would like to delete the Array and only have the raw data from inside the Array
You can use join() and join the array of string with , also use map() to add "" around string
const arr = ["572a2b2c-e495-4f98-bc0a-59a5617b488c", "2d50c44a-0f94-478b-91b6-bb0cd8287e70"]
console.log(arr.map(x => `"${x}"`).join(','))
Array.prototype.toString() method will coerce all array elements to string type and give you the entire array as a single string with elements separated by comma:
const arr = ["572a2b2c-e495-4f98-bc0a-59a5617b488c", "2d50c44a-0f94-478b-91b6-bb0cd8287e70"];
const arr_toString = arr.toString();
// "572a2b2c-e495-4f98-bc0a-59a5617b488c,2d50c44a-0f94-478b-91b6-bb0cd8287e70"
If you want the array as single string separated by comma and each element wrapped by "":
const arr = ["572a2b2c-e495-4f98-bc0a-59a5617b488c", "2d50c44a-0f94-478b-91b6-bb0cd8287e70"];
const wanted_result = arr.map(elm => `"${elm}"`).toString();
// "572a2b2c-e495-4f98-bc0a-59a5617b488c","2d50c44a-0f94-478b-91b6-bb0cd8287e70"
Array.prototype.map() executes whatever function you supply on all the elements of the array and return the returned value of the function. So the function I used is:
elm => `"${elm}"` - which takes each elm and return it wrapped by ""

Convert array of array's each array into array of string

I am trying to convert an array of array's each array into a string.
I know the method flat where all the array of the array becomes a single array but this is not solving my full purpose.
array = [['ba','ab'],['bab','abb']]
my tried code is:
let merged = array.map(a => {
console.log(a)
a.reduce((a, b) => a.concat(b), []);
})
console.log(merged);
Expected output is: [['ba,ab'],['bab, abb']]
You can use Array.prototype.join() for this purpose. From the documentation:
The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
Like the following:
const array = [['ba', 'ab'], ['bab', 'abb']];
const result = array.map(e => e.join(','));
console.log(result);
Hope that helps!
You could map the joined values.
var array = [['ba', 'ab'], ['bab', 'abb']],
result = array.map(a => a.join(', '));
console.log(result);
With respect to your comment on #norbitrial answer.
Plus a little JS type conversion hack (just for education, you'd better use join(",")). And I think you should accept his answer.
const array = [['ba', 'ab'], ['bab', 'abb']];
const result = array.map(e => ["" + e]);
console.log(result);

JavaScript : Can I sort String within an array (not a normal use of sort possible)

I want to sort string inside an array, not a normal sorting because if I do so the result will be:
var a = ["dcb","acb","gfe"];
console.log(a.sort());
the answer would be:
["acb","dcb","gfe"]
which I don't want, the sorted array I want is sorting of string inside the array, For eg:
var a = ["dcb","acb","gfe"];
expected answer :
["bcd","abc","efg"]
hope my question is clear to you :)
Use Array.map() and sort each string seperatly:
const arr = ["dcb","acb","gfe"];
const result = arr.map(str => str
.split('')
.sort()
.join('')
)
console.log(result);
To perform an operation on each element of an array (in this case, sort a string), use a loop. The Array.prototype.map function is an appropriate "loop-function" when you want to map an array of length n to an array of the same length (i.e. when you want to transform each element of an array).
let a = ["dcb", "acb", "gfe"];
let sorted = a.map(a => [...a].sort().join(''));
console.log(sorted);
The .map() method iterates through each element of the array.
Use the ES6 arrow function and Destructuring assignment operator to simplify the code, if you want to use ES5 the use regular function and use the .split('') method.
The .sort() method to sort the individual characters after splitting it.
The .join('') method to joining them back.
Example (ES6):
let a = ["dcb","acb","gfe"];
let sorted = a.map( s => [...s].sort().join('') );
consloe.log(sorted);
Example (ES5):
let a = ["dcb","acb","gfe"];
let sorted = a.map(
function(s) {
return s.split('').sort().join('');
});
consloe.log(sorted);

A nested array of string to number

I'm looking to convert a nested array of the type string to type float, or alternatively parsing it from a text file. Format is something along the lines of this [45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]
The first step would be to create valid JSON from your string.
If your input will always follow the schema you showed us, you could just prepend and append brackets to the string. This is not a pretty solution though. You should first check if you can get valid JSON in the first place.
A solution could look like this, provided that the input string will always follow the format of "[float, float], [float, float]":
const input = "[45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]";
// Add brackets in order to have valid JSON.
const arrayString = "[" + input + "]";
// Parse the string into an object.
const parsedArray = JSON.parse(arrayString);
// Flatten the nested array to get a one dimensional array of all values.
var flattenedArrays = [].concat.apply([], parsedArray);
// Do something with your values.
flattenedArrays.forEach(floatValue => console.log(floatValue));
You can use JSON.parse, if your numbers are actually numbers in a JSON (serialized without quotes).
let test = "[[3, 4.2], [5, 6]]";
let test2 = JSON.parse(test);
console.log(test2);
Otherwise you can simply convert your array of array of strings to array of array of numbers using + and some array mapping. :
let test = [["3", "4.2"], ["5", "6"]];
let test2 = test.map((x) => x.map((y) => +y));
console.log(test2);
Of course, you can combine both solutions if for some reason you don't control the input and have a JSON containing strings.
This thread shows you how to loop through an array of strings to convert it to an array of floats.
i hope this will work..
var input = [[45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]]
var output = [];
input.forEach(o => {
o.forEach(s => parseFloat(s))
output.push(o);
})
console.log(output);

Categories

Resources