I have below scenarios to handle.
let data = [
[ "ALISHA", "SUICA", "PASMO" ],
[ "HARMONY" ],
[ "OCTOPUS" ]
]
let data1 = [
[ "ALISHA", ],
[ "HARMONY" ],
[ "OCTOPUS", "SUICA", "PASMO" ]
]
For both of the above data, i want the result to look like this.
let result = [
[ "ALISHA" ],
[ "HARMONY" ],
[ "OCTOPUS" ],
[ "SUICA" ],
[ "PASMO" ]
]
Can someone please let me know how to achieve this. I tried the following but no success
let result = []
for (let i = 0; i < data.length; i++) {
let split = data[i].split(","); // just split once
result.push(split[0]); // before the comma
}
we will use forEach method on main array inside forEach we will use if condition if is array and length more than 1 will add another forEach method and push sub array to main array after that remove sub array
look like that
let data = [
["ALISHA"],
["HARMONY"],
["OCTOPUS", "SUICA", "PASMO"]
]
data.forEach((cur, index) => {
if (Array.isArray(cur) && cur.length > 1) {
cur.forEach(cur => data.push([cur]))
data.splice(index, 1);
}
})
console.log(data)
Uses Array.reduce extract all elements, then convert to [string] by Array.map.
const data = [
[ "ALISHA" ],
[ "HARMONY" ],
[ "OCTOPUS", "SUICA", "PASMO" ]
]
console.log(
data.reduce((pre, cur) => [...pre, ...cur], []).map(item => [item])
// data.reduce((pre, cur) => pre.concat(...cur), []).map(item => [item]) // different methods but same logic (uses Array.concat instead of spread operator)
)
You can use flat and map
const data = [["ALISHA"], ["HARMONY"], ["OCTOPUS", "SUICA", "PASMO"]];
const result = data.flat().map((a) => [a]);
console.log(result);
Related
I have two array arr1 where qid is unique and arr2 where markid is unique. I want match qid and markid and result from that result arr3
arr1=[subjectwisequetion:[questions:
[{qid:"1",anskey:"c"}],
[{qid:"2",anskey:"c"}],
[{qid:"3", anskey:"c"}]
]
]
arr2=[
{markid:"2", markstatus:"2"},
{markid:"3", markstatus:"1"}
]
arr3= [subjectwisequetion:
[questions:[
{qid:"1", anskey:"c", markstatus:"null"}
],
[
{qid:"2", anskey:"c", markstatus:"2"}
],
[
{qid:"3", anskey:"c" , markstatus:"1"}
]
]
]
try this, it works for me:
let arr11 = [{qid:"1", anskey:"c"}, {qid:"1",anskey:"c"},{qid:"1", anskey:"c"}]
let arr22 = arr2=[ {markid:"2", markstatus:"2"},{markid:"3", markstatus:"1"}]
let arr33 = arr11.map((item, i) => Object.assign({}, item, arr22[i]));
I've got a constant result like this :
result: Map<string, string[]>
When I do a console.log(result) the output is :
Map {
'toto' => [ 'a-1', 'a-2' ],
'tata' => [ 'b-1', 'b-2' ],
'titi' => [ 'c-1', 'c-2' ],
}
What I want to have, it's a constant globalResult with all values like this:
const globalResult = [ 'a-1', 'a-2','b-1','b-2','c-1','c-2' ]
How can I do this ?
Thanks
You can get map values into an array and then use flat() method on it like:
const myMap = new Map().set('toto', ['a-1', 'a-2']).set('tata', ['b-1', 'b-2'])
const arr = [...myMap.values()].flat()
console.log(arr)
You can use Array.from to covert map values into a flat array
const map = new Map();
map.set('a',11)
map.set('b',22)
map.set('c',33)
const array = Array.from(map.values())
console.log(array)
You could get the values of the properties and flat the arrays.
const
object = { toto: ['a-1', 'a-2'], tata: ['b-1', 'b-2'], titi: ['c-1', 'c-2'] },
array = Object.values(object).flat();
console.log(array);
Use forEach function.
const obj = {
'toto' : [ 'a-1', 'a-2' ],
'tata' : [ 'b-1', 'b-2' ],
'titi' : [ 'c-1', 'c-2' ],
}
const arr = [];
Object.values(obj).forEach(value=>arr.push(...value));
console.log(arr);
I've got a matrix where rows don't necessarily have the same length:
The following are musical tokens in the format of solfege.
const notes = [
[ 'do5', 'mi5' ],
[ 'mi6', 'so6', 'ti6', 're7' ],
[ 'so7', 'ti7', 're8', 'fa8' ],
[ 'la3', 'do4', 'mi4' ],
[ 'fa2', 'la2' ],
[ 're2' ],
[ 'ti1', 're2', 'fa2' ]
];
I have a function that converts these tokens into equivalent alphabetic tokens (for example: fa2 would be converted to F2 using my function).
I would like to be able to iterate over this matrix, and return the transformed matrix, which should retain the same dimensions.
Thanks,
Nakul
Here's what you probably want:
const notes = [
[ 'do5', 'mi5' ],
[ 'mi6', 'so6', 'ti6', 're7' ],
[ 'so7', 'ti7', 're8', 'fa8' ],
[ 'la3', 'do4', 'mi4' ],
[ 'fa2', 'la2' ],
[ 're2' ],
[ 'ti1', 're2', 'fa2' ]
];
// replace this function with your own converter
function convert(note) {
return note.toUpperCase();
}
for (let i = 0; i < notes.length; i++) { // for each row
// map will iterate through the row, converting each note
notes[i] = notes[i].map(convert);
}
The part map(convert) is just a shorter form of map(note => convert(note)).
This is not very efficient, as map() will create a new array for each row, but in your case it's probably more important that the code is readable rather than performant, so that's fine.
You can use the new Array.prototype.flat() function, but, if you want wider support (.flat() is ignored by both Edge and IE), then I would use two for..of loops.
const arr = [
[ 'do5', 'mi5' ],
[ 'mi6', 'so6', 'ti6', 're7' ],
[ 'so7', 'ti7', 're8', 'fa8' ],
[ 'la3', 'do4', 'mi4' ],
[ 'fa2', 'la2' ],
[ 're2' ],
[ 'ti1', 're2', 'fa2' ]
];
// Modern JavaScript
for (const item of arr.flat()) {
console.log(item);
}
console.log('----');
// More widely supported JavaScript
for (const subarray of arr) {
for (const subitem of subarray) {
console.log(subitem);
}
}
i am working on lodash in which i need to filtered the data from big collection of array.The collection of array is this type of data:
[ { poll_options: [ [Object] ],
responder_ids: [ '5a7189c14615db31ecd54347', '59ffb41f62d346204e0a199b' ],
voted_ids: [ '5a7189c14615db31ecd54347' ],
_id: 5a7878833a1bf4238ddc5cef },
{ poll_options: [ [Object] ],
responder_ids: [ '5a7189c14615db31ecd54347' ],
voted_ids: [ '5a7189c14615db31ecd54347' ],
_id: 5a787756217db51698ea8fd6 } ]
I want to filter array of which contain the value of ids which is not in voted_ids(i.e for first object it should return this 59ffb41f62d346204e0a199b nd for second collections it should return empty array) that means i have to return only those values which are not on voted_ids but in responder_ids. my code is this
_.map(polls,(poll) => {
// console.log(poll.responder_ids)
return _.filter(poll.responder_ids,(responder) => {
return _.find(poll.voted_ids,(voted) => {
return !_.includes(responder,voted)
})
but it does not returning filtered array istead it return whole collections.Where I am doing wrong??
Now its returning result like this...
[ [ '59ffb41f62d346204e0a199b' ], [] ]
I want single array not multiarray.
You are using _.filter in a wrong way.
Filter iterates over all items in your array. If the filter function returns true the item will be returned in the filtered array and if it returns false it will not be returned.
You however are returning an array, which results to truthy and therefore all items are returned.
What you want is something like:
const polls = [
{
poll_options: [ '[Object]' ],
responder_ids: [ '5a7189c14615db31ecd54347', '59ffb41f62d346204e0a199b' ],
voted_ids: [ '5a7189c14615db31ecd54347' ],
_id: '5a7878833a1bf4238ddc5cef'
},
{
poll_options: [ '[Object]' ],
responder_ids: [ '5a7189c14615db31ecd54347' ],
voted_ids: [ '5a7189c14615db31ecd54347' ],
_id: '5a787756217db51698ea8fd6'
}
];
let ids = [];
for (let i = 0; i < polls.length; i++) {
ids = [...ids, ...polls[i].responder_ids.filter(id => {
return !polls[i].voted_ids.includes(id);
})];
}
console.log(ids);
This is not right way to use filter function. In the callback function you should return some boolean value so the array could be filtered by that criteria.
If I understand you correctly you want to filter through array to get array which will contain all results when the id is in the responder_ids but no in the voted_ids. It could be resolved in various ways, i.e.:
_.filter(polls, poll => _.findIndex(poll.responder_ids, id => id === '59ffb41f62d346204e0a199b') > -1 && _.findIndex(poll.voted_ids, id => id === '59ffb41f62d346204e0a199b') === -1;
);
I'm working with this structure:
[
[
{
"comments":"asd",
"movement":"Back Squat",
"userID":"wDHZv3OL55SIymHkhMUejNleNkx1",
"weight":"330"
}
],
[
{
"comments":"asd",
"movement":"Bench Press",
"userID":"wDHZv3OL55SIymHkhMUejNleNkx1",
"weight":"100"
}
],
[
{
"comments":"Comment",
"movement":"Clean",
"userID":"wDHZv3OL55SIymHkhMUejNleNkx1",
"weight":"195"
}
],
[
],
[
],
[
{
"comments":"Front squat comment alpha",
"movement":"Front Squat",
"userID":"wDHZv3OL55SIymHkhMUejNleNkx1",
"weight":"315"
}
],
[
],
[
],
[
],
[
],
[
],
[
{
"comments":"abc",
"movement":"Strict Press",
"userID":"wDHZv3OL55SIymHkhMUejNleNkx1",
"weight":"155"
}
]
]
This is the input I'm using in JSON format. As you can see there are multiple empty arrays.
How would I go about filtering through these arrays and remove the empty ones?
Use the native Array#filter or lodash's _.filter(), and keep the sub arrays with length other than 0.
Array#filter
var arrs = [[{"comments":"asd","movement":"Back Squat","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"330"}],[{"comments":"asd","movement":"Bench Press","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"100"}],[{"comments":"Comment","movement":"Clean","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"195"}],[],[],[{"comments":"Front squat comment alpha","movement":"Front Squat","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"315"}],[],[],[],[],[],[{"comments":"abc","movement":"Strict Press","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"155"}]];
var result = arrs.filter(function(sub) {
return sub.length;
});
console.log(result);
Lodash's _.filter() with _.size:
var arrs = [[{"comments":"asd","movement":"Back Squat","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"330"}],[{"comments":"asd","movement":"Bench Press","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"100"}],[{"comments":"Comment","movement":"Clean","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"195"}],[],[],[{"comments":"Front squat comment alpha","movement":"Front Squat","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"315"}],[],[],[],[],[],[{"comments":"abc","movement":"Strict Press","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"155"}]];
var result = _.filter(arrs, _.size);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
If all the items in the top level array are arrays then you could lodash's reject with the isEmpty predicate.
let result = _.reject(data, _.isEmpty);
isEmpty will also return true for empty objects amongst other thing so if your top level array can contain such items then to just remove empty arrays you could compose a new function to return just empty arrays and use that as the predicate to reject:
let isEmptyArray = item => _.isArray(item) && _.isEmpty(item);
let result = _.reject(data, isEmptyArray);
Test each array in turn to see if it has a non-zero (truthy) length. If it does, put it in your new array.
var array_of_arrays = [[1], [1,1], [], [], [1]];
var array_of_non_empty_arrays = array_of_arrays.filter((array) => array.length);
console.log(array_of_non_empty_arrays);