How can i take the objects inside in the array? - javascript

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 ""

Related

How can I get a full string that contains a substring in Javascript?

For example:
I have a array
const tags = ['size-1', 'size-2', 'discount-xyz']
In this case to check if I have a substring with discount in it, I have converted the array to a string
const arrayToString = tags.toString();
The output:
const tagsArrayToString = size-1,size-2,discount-wyx;
And I check if with a IF statement like this:
if ( tagsArrayToString.indexOf("discount") !== -1 ) { doSomething }
So far so good. But how can I get the full String like "discount-xyz"?
I wouldn't convert the tags array to a string - you already have the strings nice and separated, and this would only make things harder.
Instead, you could filter the array:
const filteredTags = tags.filter(t => t.includes('discount'));
Or, if you know there's just one such string, you could use find to get it:
const relevantTag = tags.find(t => t.includes('discount'));
Find the index of the discount tag using findIndex method, in turn find the tag itself via the index of the array.
const index = tags.findIndex(t => t.indexOf('discount') !== -1);
const discountTag = tags[index];

filter values from an array of strings from another array of objects

I am trying to get only those strings which are not present in array of objects
var objects = [{name:'a',is:false},{name:'b',is:false},{name:'c',is:false}];
var strings = ['a','b','z','x'];
let result = strings.filter(o1 => !objects.includes(o2=> o2.name === o1));
console.log(result)
so the result should be only 'z' and 'x'
From your objects array, you can create Map (lookup) which has keys as the name property and values as the negated version of the is property.
Map {
'a': true,
'b': true,
'c': true
}
You can then use this to lookup to filter your array of strings. If the Map has a value which is true then you can remove it from your array (by returning false), otherwise, if the Map doesn't have the current string, you can keep it in the array. Creating a map/object by preprocessing your objects array saves you from needing to use an inner loop inside of your filter(), improve the overall efficiency of your code if your array sizes increase.
const objects = [{name:'a',is:false},{name:'b',is:false},{name:'c',is:false}];
const strings = ['a','b','z','x'];
const lookup = new Map(objects.map(({name, is}) => [name, !is]));
const result = strings.filter(v => !lookup.get(v));
console.log(result);
Your approach was very close. However, the .includes() method doesn't accept a callback function like you're providing it with (.includes() will search your array for that same function object references your providing it with)
const cb = v => v; // fake callback
const arr = [cb]; // some array contains that callback
console.log(arr.includes(cb)); // providing the callback as a function to includes
// => true, as the `cb` function is inside of `arr`
If you want to provide your own "includes" logic, you can use .some() instead:
var objects = [{name:'a',is:false},{name:'b',is:false},{name:'c',is:false}];
var strings = ['a','b','z','x'];
let result = strings.filter(o1 => !objects.some(o2 => o2.name === o1));
console.log(result)
If you're curious, the above logic with .some() has a time complexity of O(N*M), whereas the Map approach has a time complexity of O(N+M), where N is the size of your strings array and M is the size of your objects array.
Used map to simplify the array and then used filter and includes to find out the strings which are not part of objects.
var objects = [{name:'a',is:false},{name:'b',is:false},{name:'c',is:false}];
var strings = ['a','b','z','x'];
let names = objects.map(dataItem => dataItem.name)
let filteredNames = strings.filter(stringItem => !names.includes(stringItem))
console.log(filteredNames)
includes now allow callback function.
instead of this use find:
var objects = [{name:'a',is:false},{name:'b',is:false},{name:'c',is:false}];
var strings = ['a','b','z','x'];
let result = strings.filter(o1 => !objects.find(o2=> o2.name === o1));
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);

Filter array by content?

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));

Categories

Resources