How to get all index of an array to new array - javascript

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

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

How to access the inner array resulting from d3.groups?

I'm struggling to understand how I can use the new d3.group and d3.groups methods. My goal is to add a dropdown menu to my d3.chart. Specifically, when I select an option, the chart displays the data for this particular individual. My problem is that I don't understand how I can access the inner array for the selected individual. For example, if I select bib nr. 5, I want to access this individual's ratio score.
I have been stuck for this problem for a long time. I appreciate your help :)
const data = d3.range(20).map(i => ({
bib: Math.floor(i / 5) + 1,
ratio: -1 + Math.random() * 5,
run: [1, 2, 3, 4, 5][i % 5],
name: ['GIRL1', 'GIRL2', 'GIRL3', 'GIRL4'][Math.floor(i / 5)]
}));
// Now I want to use d3.groups
const skiers = d3.groups(data, d => d.bib)
//Logging this gives me a nested array.
console.log(skiers)
// I want to access the inner array for a particular individual, but how can I accomplish this?
// I have tried to use .map()
console.log(skiers.map(d => d.run)) //This gives me undefines
<script src="https://unpkg.com/d3#6.2.0/dist/d3.min.js"></script>
Use filter() to get all the objects where d[0] equals the bib you're trying to collect;
const data = d3.range(20).map(i => ({
bib: Math.floor(i / 5) + 1,
ratio: -1 + Math.random() * 5,
run: [1, 2, 3, 4, 5][i % 5],
name: ['GIRL1', 'GIRL2', 'GIRL3', 'GIRL4'][Math.floor(i / 5)]
}));
const skiers = d3.groups(data, d => d.bib)
const bibToFind = 3;
// Array with objects
const bibFound = skiers.filter(d => d[0] === bibToFind);
// Objects only
const bibObjects = bibFound[0][1];
console.log(bibFound, bibObjects);
<script src="https://unpkg.com/d3#6.2.0/dist/d3.min.js"></script>
Whe you use .map you're iterating only the first level of nested array
[
[ // "d" is this array in your map function
1,
[
{
"bib": 1,
"ratio": 0.6494187230703661,
"run": 1,
"name": "GIRL1"
},
{
"bib": 1,
"ratio": -0.2740398059491158,
"run": 2,
"name": "GIRL1"
},
{
"bib": 1,
"ratio": 3.3705616486650136,
"run": 3,
"name": "GIRL1"
},
{
"bib": 1,
"ratio": 0.9649181479003297,
"run": 4,
"name": "GIRL1"
},
{
"bib": 1,
"ratio": 1.7259011213023032,
"run": 5,
"name": "GIRL1"
}
]
]
]
const data = d3.range(20).map(i => ({
bib: Math.floor(i / 5) + 1,
ratio: -1 + Math.random() * 5,
run: [1, 2, 3, 4, 5][i % 5],
name: ['GIRL1', 'GIRL2', 'GIRL3', 'GIRL4'][Math.floor(i / 5)]
}));
// Now I want to use d3.groups
const skiers = d3.groups(data, d => d.bib)
//Logging this gives me a nested array.
console.log(skiers[0]) // first level
console.log(skiers[0][1]) // second level take second element
console.log(skiers[0][1][0]) // here you have the first object
// so you can map over the specific level of the nested array
console.log(skiers[0][1].map(d => d.run)) // no mo undefined
//or you can convert the nested array to a simple array if if that what are you looking
console.log("flatmap",skiers.flatMap(d=> d[1]))
// and the acces each run property
console.log("flatmap",skiers.flatMap(d=> d[1]).map(d => d.run))
<script src="https://unpkg.com/d3#6.2.0/dist/d3.min.js"></script>
The only difference between d3.group and d3.groups is that the former returns a Map, while the latter returns an array. Therefore, if you use d3.group, the only thing you'll need to get the array (say bib 1) is:
skiers.get(1);
Here is the demo:
const data = d3.range(20).map(i => ({
bib: Math.floor(i / 5) + 1,
ratio: -1 + Math.random() * 5,
run: [1, 2, 3, 4, 5][i % 5],
name: ['GIRL1', 'GIRL2', 'GIRL3', 'GIRL4'][Math.floor(i / 5)]
}));
// Now I want to use d3.groups
const skiers = d3.group(data, d => d.bib)
const innerArray = skiers.get(1);
console.log(innerArray);
<script src="https://unpkg.com/d3#6.2.0/dist/d3.min.js"></script>

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

Array of array to object - javascript

I am looping to convert the array of array to object, but the final object has only the last item in the object. I am getting confused because you cant push in an object like array, and the number of loop is getting me frustrated. need help
here is the JSbin : http://jsbin.com/torawovicu/edit?js,console
Also how to get the object the same order as the array?
this is what the result should look like:
var newResult =
[
{itemcode: 1, item: 'Pen', 'cashier' : 'Sam'},
{itemcode: 2, item: 'Eraser', 'cashier' : 'Kim'}
]
Here is my code
var list = [
[
['itemCode', 1],
['item', 'Pen'],
['cashier', 'Sam']
],
[
['itemCode', 2],
['item', 'Eraser'],
['cashier', 'Kim']
]
]
//console.log(people.length);
function result(array) {
var newObj = {};
var newArr = [];
for (var x in array) {
//console.log(array[x])
var item = array[x];
for (var y in item) {
var itemSingle = item[y]
//console.log(itemSingle);
for (i = 0; i < itemSingle.length; i = i + 2) {
newObj[itemSingle[i]] = itemSingle[i + 1];
}
}
}
return newObj;
}
console.log(result(list));
You can use Array.prototype.map and Array.prototype.reduce to get the desired result like this:
var list = [
[
['itemCode', 1],
['item', 'Pen'],
['cashier', 'Sam']
],
[
['itemCode', 2],
['item', 'Eraser'],
['cashier', 'Kim']
]
];
function result(arr) {
return arr.map(function(sub) {
return sub.reduce(function(acc, e) {
acc[e[0]] = e[1];
return acc;
}, {});
})
}
console.log(result(list));
Note: you can't relly on the order of the object poperties.
You have to use one loop to iterate over main array and then run loops to iterate over each array item (which also is an array) to construct object with properties you need. You can use map as main loop to return new array with items constructed inside each iteration. To construct those items you can use forEach:
var list = [
[
['itemCode', 1],
['item', 'Pen'],
['cashier', 'Sam']
],
[
['itemCode', 2],
['item', 'Eraser'],
['cashier', 'Kim']
]
];
function result(array) {
let newArray = array.map(function(nestedArray) {
let obj = {};
nestedArray.forEach(function(item) {
obj[item[0]] = item[1];
});
return obj;
});
return newArray;
}
console.log(result(list));
There are two problems.
First, you're never adding the objects to the array or returning the array, you're just returning the object.
Second, you're using the same object each time through the loop, just replacing its properties. You need to create a new object each time, and then add it to the array.
It's also not a good idea to use for-in to iterate an array, use a numeric for loop (or the Array.prototype.forEach() function). See Why is using "for...in" with array iteration a bad idea?
var list = [
[
['itemCode', 1],
['item', 'Pen'],
['cashier', 'Sam']
],
[
['itemCode', 2],
['item', 'Eraser'],
['cashier', 'Kim']
]
]
//console.log(people.length);
function result(array) {
var newArr = [];
for (var x = 0; x < array.length; x++) {
var newObj = {};
var item = array[x];
for (var y = 0; y < item.length; y++) {
var itemSingle = item[y];
for (var i = 0; i < itemSingle.length; i+=2) {
newObj[itemSingle[i]] = itemSingle[i + 1];
}
}
newArr.push(newObj);
}
return newArr;
}
console.log(result(list));
You can do it with a single line:
const newResult = list.map(a => a.map(([k,v]) => ({[k]: v})));
const show = msg => {console.log(JSON.stringify(msg));};
const list = [
[
['itemCode', 1],
['item', 'Pen'],
['cashier', 'Sam']
],
[
['itemCode', 2],
['item', 'Eraser'],
['cashier', 'Kim']
]
];
const newResult = list.map(a => a.map(([k,v]) => ({[k]: v})));
show(newResult);
Your question could possibly be addressed by using a relatively recent feature in JavaScript: map objects.
Note that when you have an array of indeterminate length where each element is itself an array that is two elements long, you can convert the outer array into a map object instead of just a plain object. e.g. const newMapObj = new Map([['a', 1], ['b', 2]]);. Entering that into a terminal and then checking console.log(newMapObj) produces the following: Map { 'a' => 1, 'b' => 2 }. In your example, you could do this with each of your two list elements/store items, i.e. you would end up with an array of 2 map objects.
Such map objects have some convenient features, such as get and has. Some people also find them frustrating because of e.g. a lack of some helpful methods used with, say, arrays, like, um, well, the map method. (Note that the map method on arrays and the map/Map data object type are two completely different things. I know, it's confusing.)
The code snippet below creates an array of such map objects, one for each outer array element (i.e. one for each store 'item'), with one simple line:
const newResult = list.map(a => new Map(a));
Unfortunately, at this point in time at least, the code snippet tool here on Stack Exchange doesn't allow us to simply show the map object using console.log the way you can with, say, a plain object or an array. As a 2nd best substitute, the code snippet below logs out some of the results of using the map objects, just to demonstrate that the map objects were in fact created.
When I do the same thing in a Mac terminal (i.e. define list as the nested arrays in your question and then calculate newResult as above), console.log(newResult) shows the following:
[ Map { 'itemCode' => 1, 'item' => 'Pen', 'cashier' => 'Sam' },
Map { 'itemCode' => 2, 'item' => 'Eraser', 'cashier' => 'Kim' } ]
In other words, it is an array of map objects instead of an array of objects.
If you're interested in this recent JavaScript feature, you should check out the MDN documentation on the Map data object.
Whether you really want to use map objects or plain objects depends on your use case. The MDN documentation linked above has a short section to help you determine whether you want to use map objects or plain objects.
const list = [
[
['itemCode', 1],
['item', 'Pen'],
['cashier', 'Sam']
],
[
['itemCode', 2],
['item', 'Eraser'],
['cashier', 'Kim']
]
];
const newResult = list.map(a => new Map(a));
console.log('The name for the 1st item is:', newResult[0].get('item'));
console.log('The cashier for the 2nd item is:', newResult[1].get('cashier'));
You will have to use 2 dimensional array for that, first you have to create one for comlumn and second for row, in example i have shown in comulmn i have added the name, and in row i have added occupation, let's code :-
data = new Array(5)
info = [0] = new Array(2)
name [0][0] = "Tom"
occu [0][1] = "Worker"
info [1] = new Array(2)
name [1][0] = "Beryl"
occu [1][1] = "engineer"
info [2] = new Array(2)
name [2][0] = "Ann"
occu [2][1] = "surgeon"
info [3] = new Array(2)
occu [3][0] = "Bill"
name [3][1] = "taxman"
info [4] = new Array(2)
name [4][0] = "Myrtal"
occu [4][1] = "bank robber"

Categories

Resources