expand and reorder an array of objects - javascript

i have and array
reservation1:[
{name:"8:30",active:true,dayindex:1},
{name:"jad",active:true,dayindex:3},
]
i need to expand the array to 9
and fill it with object with name null active false dayindex: between 0 and 10 in order
the output needed is
output =[
{name:"",active:false,dayindex:0}
{name:"8:30",active:true,dayindex:1}
...
i tried this for expanding
it worked for expanding but i couldnt reorder it as i wanted

You can sort you array after adding others elements:
var reservation = [
{name:"8:30",active:true,dayindex:1},
{name:"jad",active:true,dayindex:3},
{name:"tony",active:true,dayindex:4},
{name:"",active:false,dayindex:6}
];
var availabeDayIndex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].filter(el => !reservation.map(it => it.dayindex).includes(el));
var sortField = 'dayindex';
reservation = [...reservation, ...Array.from(Array(9 - reservation.length), (val, key) => ({name: null, active: false, dayindex: availabeDayIndex[key]}))].sort((a, b) => a[sortField] - b[sortField]);
console.log(reservation);

Related

What is the best way to check multidimensional array in typescript or javascript to detect duplicate values?

I have two dimensional array like below:
array = [ [ 1, 1 ], [ 1, 2 ], [ 1, 1 ], [ 2, 3 ] ]
I want to compare value in array index to see if they have duplicate values. For example
array[0] = [1,1];
array[1] = [1,2];
array[2] = [1,1];
We can see that value at index 0 and 2 are same that is [1,1]. So, in that case I want to have true flag. What is the most efficient way to do it? or What are different ways to do it? Any kind of suggestion or help would be great with bit of explanation. Thanks in advance.
You can achieve it by convert the inner array elements into a string just for the comparison purpose.
Demo :
const arr = [[ 1, 1 ], [ 1, 2 ], [ 1, 1 ], [ 2, 3 ]];
const stringConversion = arr.map((item) => JSON.stringify(item))
const duplicateElements = stringConversion.filter((item, index) => stringConversion.indexOf(item) !== index)
console.log(duplicateElements.length ? true : false);
So, what I think you can do is:
Cycle every element of the multidimensional array.
Then check if the two element are the same by accessing the "row" with the index 0 and index 1
I think you can use different way to loop the array, this is what I tried:
// DECLARATIONS
array = [[ 1, 1 ], [ 1, 2 ], [ 1, 1 ], [ 2, 3 ]];
// LOOPING THE ARRAY
for (row of array)
{
// RETURN TO CONSOLE OR WHATEVER THE BOOLEAN VALUE
console.log(row[0] == row[1]);
}
String to convert array to a one-dimensional array of strings and some to check if any element is duplicated:
const arr = [[1, 1], [1, 2], [1, 1], [2, 3]];
const result = arr.map(String).some((v, i, a) => a.indexOf(v) !== i);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Reorder an array of values in an object in Javascript

I have the following object that I am trying to sort so that the labels are "High, mid, low" all of the time. The order I get them are not always the same so I wanted to add another layer of ordering to ensure that I get "high, mid, low"
Before:
status:{
label:['mid', 'high', 'low'],
data:[4, 3, 1]
}
After:
status:{
label:['high', 'mid', 'low'],
data:[3, 4, 1]
}
The easiest way to sort those two arrays "linked" is by temporarily combining them into one array:
const status = {
label: ['mid', 'high', 'low'],
data: [4, 3, 1]
};
// Combine the two arrays into an array of pairs
const pairs = status.label.map((label, index) => [label, status.data[index]]);
console.log('pairsBefore', pairs); // [ ['mid', 4 ], ['high', 3 ], ['low', 1 ]]
// Used for sorting
const ORDER = ['high', 'mid', 'low'];
// Sort the pairs
pairs.sort((a, b) => {
const [labelA, dataA] = a;
const [labelB, dataB] = b;
// Gives 0 for 'high', 1 for 'mid' and 2 for 'low'
const indexA = ORDER.indexOf(labelA);
const indexB = ORDER.indexOf(labelB);
// Substract for A and B, see how Array.prototype.sort works
return indexA - indexB;
});
console.log('pairsAfter', pairs); // [ ['high', 3 ], ['mid', 4 ], ['low', 1 ]]
// Split it back into two arrays
const statusSorted = {
label: pairs.map(pair => pair[0]),
data: pairs.map(pair => pair[1]),
};
console.log('statusSorted', statusSorted);
//{
// label: ['high', 'mid', 'low'],
// data: [3, 4, 1],
//}

How to get all index of an array to new array

I have an array of arrays that I am trying to map. But I am having an issue with my mapping because mapping all indexes not just the one I want it to be mapping. I figured I can work my way around this by creating a new array of only of the data I am trying to map.
How can I push all index 2 into a new array? I have not been able to find an example of what I am attempting to do.
I am expecting an outcome of a new array that equals [231, 431, 481]
Here is an example of my code:
const array = [ ["name", 1, 231], [ "name", 2, 431], ["name", 3, 481] ]
console.log(array)
let percentage = array.map(function (num, i) {
return 100 * ((num - array[i - 1]) / (array[i - 1]));
});
You can do this
const array = [ ["name", 1, 231], [ "name", 2, 431], ["name", 3, 481] ]
const arrayNew = array.map(x => x[2])
// arrayNew === [231, 431, 481]
Check the inline comments
const array = [
["name", 1, 231],
["name", 2, 431],
["name", 3, 481],
];
// If you know, there will be 3 elements in array
console.log(array.map(([, , last]) => last));
console.log(array.map(({ 2: last }) => last));
// For any size of sub array, get the last element in map
console.log(array.map((arr) => arr[arr.length - 1]));

Mapping an Array Based on Another Array

I'm working on a project where I need to change the values of one array should the first index of one of its nested arrays be found within the second array. For example:
Array One
[12345, [67890, 1], [09876, 2]]
Array Two
[
[
180547,
'180547 text',
'more text',
...etc
], [
67890,
'67890 text',
'more text',
...etc
],
...etc
]
I need to iterate through each of the nested arrays in Array One and check if the first value in each nested array is present in the any of the arrays in Array Two. From there, I need to copy Array Two's array, and replace the first value of the nested array in Array One.
I know that was probably a little confusing, so here's an example output of the above arrays:
Output
[12345, [[67890, '67890 text', 'more text', ...etc], 1], [09876, 2]]
ES6+ is preferred, but not necessary.
EDIT:
As asked for, so given -
Function jargon aside, here's the best I was able to come up with on my own:
gid.steal()
.then(dataset => {
let o = dataset.forEach(group => {
group.map((person, i) => {
i === 0 ? person : rows.forEach(row => {
row[0] === person[0] && row[row.length - 1] === '-3' ? [row, person[1]] : null
})
})
})
console.log(o)
})
.catch(err => rej(err))
//dataset would be Array One and rows would be Array Two
This returns undefined
I have a feeling I'm either trying to get too complicated/clever with it, or I'm totally out of bounds on this method.
Figured it out. It turns out I was definitely trying to be more complicated than I needed to be. I just needed some simple maps and a filter.
let arr1 = [
['john', 1, 2, 3, 4, '5'],
['jane', 1, 2, 3, 4, '5'],
['jane', 1, 2, 3, 4, '-3'],
['joe', 1, 2, 3, 4, '-3']
]
let arr2 = [
['number', ['jane', 1]]
]
const fx = data => {
return data.map(s => {
return s.map((t, u) => {
return u === 0
? t
: [arr1.filter(v => v[0] === t[0] && v.indexOf('-3') >= 0)[0], t[1]]
})
})
}
console.log(fx(arr2))

Filter array of 3-item arrays by third item; get result set without third items [duplicate]

This question already has answers here:
Filter Array of Array for values inside nested array
(4 answers)
Only specific 'columns' from a 2d javascript array
(4 answers)
Closed 4 months ago.
I have these variables:
var arr = [
[ "name1", 2, "filter1" ],
[ "name2", 5, "filter2" ],
[ "name3", 8, "filter3" ],
[ "name4", 1, "filter2" ]
];
// This variable may have values: `"filter1"`, `"filter2"`, `"filter3"`.
var filter = "filter2";
How can I filter the array arr according to the filter variable values?
My example must return this:
[
[ "name2", 5 ],
[ "name4", 1 ]
]
Beside the filtering, you need to get only the first two elements of the inner arrays.
Array#filter returns the same elements in the array. For getting the wanted items without the filter item, you need to return either the first two objects, or filter the items with the given filter as well (proposal 2).
var array = [['name1', 2, 'filter1'], ['name2', 5, 'filter2'], ['name3', 8, 'filter3'], ['name4', 1, 'filter2']],
filter = 'filter2',
result = array.filter(a => a[2] === filter).map(a => a.slice(0, 2));
console.log(result);
var array = [['name1', 2, 'filter1'], ['name2', 5, 'filter2'], ['name3', 8, 'filter3'], ['name4', 1, 'filter2']],
filter = 'filter2',
result = array
.filter(a => a.some(v => v === filter))
.map(a => a.filter(v => v !== filter));
console.log(result);
By using filter method you can easily test what you want and only return the match elements
var arr = [['name1', 2, 'filter1'], ['name2', 5, 'filter2'],['name3', 8, 'filter3'], ['name4', 1, 'filter2']];
var filter = 'filter2';
var result = arr.filter(function(res){
return res[2] == filter;
}).map(function(filtered){
return filtered.slice(0,2);
});
console.log(result);

Categories

Resources