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

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

Related

How to get the years from an array of dates in order

I have this array:
var array1 = ['9/2022','7/2020','11/2021','12/2020','2/2020','4/2021','10/2021'];
How can I get the years from it in order? So the result would be this:
result = ['2020','2021','2022'];
Do I have to change the array to a new Date() format and sort, or how would be the best way ? Any Suggestion ?
Using a combination of ... , Set , .map() and .sort(). This can be done in one line.
... -> destructures array into individual items.
new Set() -> make a set out of the new items.
map() -> runs a loop and map the array into a new one.
split() -> breaks a string into array.
sort() -> sorts an array.
var array1 = ['9/2022','7/2020','11/2021','12/2020','2/2020','4/2021','10/2021'];
console.log([...new Set(array1.map(x => x.split('/')[1]))].sort());
You can easily achieve this result using Set and map
var array1 = [
"9/2022",
"7/2020",
"11/2021",
"12/2020",
"2/2020",
"4/2021",
"10/2021",
];
const result = [...new Set(array1.map((s) => s.split("/")[1]))].sort();
console.log(result);
You can map to get only the years, and then sort the results. Then you instantiate a Set which removes all duplicate entries.
new Set(['9/2022','7/2020','11/2021','12/2020','2/2020','4/2021','10/2021']
.map(dateAsString => dateAsString.split('/')[1])
.sort());
simply you can use map method to iterate over your array and then get every element and split them or separate them using Regex.
const array1 = ['9/2022','7/2020','11/2021','12/2020','2/2020','4/2021','10/2021'];
// separate each data into month and year and get the years in the result array
const result = array1.map(data => data.split("/")[1])
// make years uinque with this simple hack
const uniqueResult = [...new Set(result)]
// now you can sort your the data
const sortedUniqueResult = uniqueResult.sort((a, b) => a - b)
console.log(sortedUniqueResult)
You can also use javascript methods chaining to convert the above snippet into one line of code:
const array1 = ['9/2022','7/2020','11/2021','12/2020','2/2020','4/2021','10/2021'];
const result = [...new Set(array1.map(data => data.split("/")[1]).sort((a, b) => a - b))]
console.log(result)
Logic
Loop through array
Generate the year array by splitting the data on /.
Generate unique items using Array.reduce
Sort the array.
const array1 = ['9/2022', '7/2020', '11/2021', '12/2020', '2/2020', '4/2021', '10/2021'];
const result = array1.reduce((acc, curr) => {
const year = curr.split('/')[1];
if (!acc.includes(year)) {
acc.push(year);
}
return acc;
}, []).sort();
console.log(result);
First convert all of your dates to strings containing the year only. You can do this using map() on the array and the split() method on each string.
Then convert the year strings into numbers by using the parseInt() function.
Sort the year numbers using the default Array.sort() method and create a new Set (only containing unique values from the given array).
Using the spread operator (...), convert that Set into an Array.
var array1 = ['9/2022','7/2020','11/2021','12/2020','2/2020','4/2021','10/2021'];
var years = [...new Set(array1.map(date => parseInt(date.split("/")[1])).sort())];
One method is to iterate through the array split the string into month and year and return only the year: (~~ converts string into integer)
var array1 = ['9/2022','7/2020','11/2021','12/2020','2/2020','4/2021','10/2021'];
var years = [...new Set(array1.map(e => ~~e.split("/")[1]))];
console.log(years.sort())

How to combine all the arrays which are inside another array and delete the last symbol in each word?

There is a 2 dimensional array:
let userGroup = [
['user1-', 'user2-', 'user3-'],
['user4-', 'user5-', 'user6-'],
['user7-', 'user8-', 'user9-']
];
How to make a single array from it and delete the symbol "-" after each element?
So the output will be: ['user1, 'user2', 'user3', 'user4', 'user5', 'user6', 'user7', etc...]
And also how to write a code which will do the same but with any number of inner arrays? For example if the "userGroup" array had more unexpected inner arrays with more users (['user11', 'user12', 'user13] etc.), what is the way to write a function which take the "userGroup" array and will do the same (delete the last element "-" in each element and combine all the elements in inner arrays into one array)?
Reduce is one way, can use also the new-ish flat method; by default it flattens only to single level but possible to define depth
userGroup.flat().map(item => item.slice(0, -1));
Try this:
console.log(userGroup.reduce((acc, curr)=> [...acc, ...curr], [])
.map(el => el.replace('-','')));
For a one liner, consider:
const mapped = userGroup.reduce((p,c) => p.concat(c), []).map(s => s.slice(0, s.length-1));
Try this
[].concat.apply([], userGroup).toString().split('-,');
Array.prototype.flat is the one you are looking for
userGroup.flat()
and then you will have the flat array for your array of arrays.
Then user the Array.prototype.map to convert the values as you like
userGroup.flat().map(m => m.replace('-', ''));
You need few things to achieve your goal.
.replace()
const u = 'user1-';
console.log(u.replace('-', ''));
.map()
const u = ["user1-", "user2-", "user3-"];
const m = u.map(i => i.replace("-", ""));
console.log(m);
.flat()
const u = [
["user1-", "user2-"],
["user3-", "user4-"]
];
console.log(u.flat());
So, combing all the 3 methods in a single statement, the below is the code:
let userGroup = [
['user1-', 'user2-', 'user3-'],
['user4-', 'user5-', 'user6-'],
['user7-', 'user8-', 'user9-']
];
let grouped = userGroup.flat().map(item => item.replace('-', ''));
console.log(grouped)

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

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

Fetch unique elements from Array of Array

I have a Array of String array i want to fetch the unique elements from that array ignoring the case. how can i fetch
Example:
List of array:
[
["java,C,Node,ReactJs"]
["c","Spring"]
["undefined"]
["asdja"]
["Java","Spring"]
["adjasjh"]
["adjasjh"]
["java"]
]
ExpectedList:
[java,C,node,reactjs,spring,..]
Join the array, change to lower case, split by comma, convert into a Set to get the unique words, and then spread back to an array:
const arr = [["java,NO,C,Node,ReactJs"],["c","Spring"],["undefined"],["asdja"],["Java","Spring"],["adjasjh", "Spring-roll"],["adjasjh"],["java", "javascript", "java-script"]];
const result = [...new Set(arr.join().toLowerCase().split(','))];
console.log(result);
Older answer - won't work in all cases:
You can join the array of arrays, and use String.match() with negative lookahead RegExp to get unique strings:
const arr = [["java,NO,C,Node,ReactJs"],["c","Spring"],["undefined"],["asdja"],["Java","Spring"],["adjasjh", "Spring-roll"],["adjasjh"],["java", "javascript", "java-script"]];
const result = arr.join()
.match(/([^,]+\b)(?!.+\1[,|$])/ig);
console.log(result);
You can use reduce and map methods to iterate array and words and also Set to return array of unique elements in the end.
const array = [["java,C,Node,ReactJs"], ["c","Spring"], ["undefined"], ["asdja"], ["Java","Spring"], ["adjasjh"], ["adjasjh"], ["java"] ]
const result = [...new Set(array.reduce((r, e) => {
return r.concat(...e.map(s => s.split(',').map(w => w.toLowerCase())))
}, []))]
console.log(result)
You can flatten your array, convert every value to lowercase, use Set to remove duplicates, and Array.from to convert it back to an array.
If your ["java,C,Node,ReactJs"] is actually: ["java","C","Node","ReactJs"] you can do it this way:
const array = [
["java","C","Node","ReactJs"],
["c","Spring"],
["undefined"],
["asdja"],
["Java","Spring"],
["adjasjh"],
["adjasjh"],
["java"]
];
const unique = Array.from(
new Set([].concat.apply([], array).map(item => item.toLowerCase()))
// ^^^ flatten array
);
console.log(unique);
You could flat the data and use a Map for keeping the first unique value without mutating it.
const flat = (r, a) => Array.isArray(a) ? a.reduce(flat, r) : r.concat(a.split(','));
var data = [["java,C,Node,ReactJs"], ["c", "Spring"], ["undefined"], ["asdja"], ["Java", "Spring"], ["adjasjh"], ["adjasjh"], ["java"]],
unique = Array.from(data
.reduce(flat, [])
.reduce((m, v) => ((l => m.has(l) || m.set(l, v))(v.toLowerCase()), m), new Map)
.values()
);
console.log(unique);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Categories

Resources