a=[
{x:1,y:1,i:"Piechart1"},
{x:2,y:1,i:"Piechart2"},
{x:3,y:1,i:"Piechart3"}
]
str=["Piechart1","Piechart3"];
I want get index by comparing array string.Output in above example should be [0,2]
Could you please let me know how to achieve in lodash ,javascript
Use .map() to map the strings to their index, and .findIndex inside the .map() callback to locate the index of the object.
var a = [{x:1,y:1,i:"Piechart1"},{x:2,y:1,i:"Piechart2"},{x:3,y:1,i:"Piechart3"}];
var str = ["Piechart1","Piechart3"];
var res = str.map(s => a.findIndex(o => o.i == s));
console.log(res);
You can chain .filter(idx => idx != -1) on the end if there's any chance of one of the strings not being in the main array.
You can use reduce() method and includes() to check if element exists in another array.
const a = [{"x":1,"y":1,"i":"Piechart1"},{"x":2,"y":1,"i":"Piechart2"},{"x":3,"y":1,"i":"Piechart3"}]
const str = ["Piechart1", "Piechart3"];
const result = a.reduce((r, {i}, ind) => {
return str.includes(i) && r.push(ind), r
}, [])
console.log(result)
maps each value in str to their index in a.
str.map((str) => a.findIndex((ele) => str === ele.i))
Related
I need to assign to "value" only the result when the condition of the map is true
const arr= [1,2,3,4,5];
value=arr.map(item => item>4 && item)
console.log(value);
result value=[false,false,false,false,5]
what i need: value=5;
You can achieve the scenario using the .filter method instead.
const arr= [1,2,3,4,5];
value=arr.filter(item => item>4 && item)
console.log(value);
Use filter!
const arr= [1,2,3,4,5];
value=arr.filter(item => item>4 && item)
console.log(value);
Add a .filter(e=>e) at the end
(Short answer I’m on the phone )
Use Array.prototype.filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Syntax
let newArray = arr.filter(callback(element[, index, [array]])[, thisArg])
Read more in MDDN
const arr= [1,2,3,4,5];
var value = arr.filter((number) => number > 4);
console.log(value)
I want to do something that seems simple but I cannot figure it out.
I want to use the javascript function 'filter' to find values in an array greater than a value and then return the indices that correspond the those filtered values (or values in that indice range from another array.
arr1 = [1,3,7,9,11];
arr1 = [2,4,8,10,12];
arr1.filter(x => x > 7);
// returns: [9,11]
// desired return: [4,5] (indices from arr1 where values from arr1 that were filtered) and/or [10,12]
// (values from arr2 where values from arr1 that were filtered)
I know the code is not right but I cannot figure out how to get desired result.
Any help would be appreciated. Thanks
You can use map in combination with filter to achieve this:
arr1.map((x, i) => [x,i]).filter(([x,i]) => x > 7).map(([x,i]) => i);
This maps the array to an array of pairs where the first element is the original number and the second is the original index. Then it filters the pairs by the first element of each pair before mapping it back to the indexes.
You can Array#reduce and do this in one run of the array by checking and transforming the data at once
const arr1 = [1,3,7,9,11];
const result = arr1.reduce((acc, x, index) => acc.concat(x > 7 ? index : []), []);
console.log(result);
You can do it like this:
var arr1 = [2,4,8,10,12];
console.log(arr1.filter(x => x>7).map(m => arr1.indexOf(m)))
returns [2, 3, 4]
The most efficient method would be to use reduce. Here I'm using array spread syntax to optionally add the index to the array used as the initial value of the accumulator.
var arr1 = [1,3,7,9,11];
var indexes = arr1.reduce((acc, cur, idx) => acc = cur > 7 ? [...acc, idx] : acc, []);
console.log(indexes);
Just add another map call and indexOf
PS: If there are duplicate values, indexOf return only first occurrence.
Alternatively, if you are not particular about filter, you can use reduce which can done with one iteration.
const arr1 = [1,3,7,9,11];
const arr2 = [2,4,8,10,12];
const filter = arr => arr.filter(x => x > 7).map(x => arr.indexOf(x));
console.log(filter(arr1))
console.log(filter(arr2))
const filter2 = arr => arr.reduce((acc, x, i) => (x > 7 && acc.push(i), acc), []);
console.log(filter2(arr1))
console.log(filter2(arr2))
from
"data":[{"ja":"大阪市"},{"en":"Osaka"}]
I want to get "ja" and "en".
I tried several ways...
data.map(function(_, i) { return i; });
it returns
array of numbers.
console.log(Object.keys(Object.values(data)));
all trials return
(2) [0, 1]
0: 0
1: 1
what can I do ??
please answer me. thank you.
Use map() and return the first key the object. You can get keys using Object.keys()
let data = [{"ja":"大阪市"},{"en":"Osaka"}]
let res = data.map(x => Object.keys(x)[0]);
console.log(res)
If you don't want to use [0] use flatMap()
let data = [{"ja":"大阪市"},{"en":"Osaka"}]
let res = data.flatMap(x => Object.keys(x));
console.log(res)
Note: The second method will also get the other properties other than first. For example
[{"ja":"大阪市","other":"value"},{"en":"Osaka"}] //["ja","other","en"];
let data = [{"ja":"大阪市"},{"en":"Osaka"}]
let res = data.reduce((arr, o) => {
return Object.keys(o).reduce((a, k) => {
if (a.indexOf(k) == -1) a.push(k);
return a;
}, arr)
}, []);
console.log(res);
we have an array like below, length of the array is not constant(may increase/decrease).
[255028AD_ABC_DE_2057,261830AD_ABC_FG_2876,.......]
My aim is to achieve only the first part of each index like below.
[255028AD,261830AD,.........]
Please help.
Try this:
var arr = ['255028AD_ABC_DE_2057', '261830AD_ABC_FG_2876'];
arr = arr.map(el => el.split('_')[0]);
console.log(arr);
With Array.map() and String.substr() functions:
var arr = ['255028AD_ABC_DE_2057', '261830AD_ABC_FG_2876' ],
result = arr.map(v => v.substr(0, v.indexOf('_')));
console.log(result);
v.indexOf('_') - to find the 1st position of _ char
v.substr(0, v.indexOf('_')) - extracting the substring starting from the position 0 to the 1st position of _ char (getting slice)
You could match the first non underscore characters and return the first item of the matching result.
var array = ['255028AD_ABC_DE_2057', '261830AD_ABC_FG_2876'],
result = array.map(s => s.match(/^[^_]+/)[0]);
console.log(result);
Something like that should work:
const arr = ['255028AD_ABC_DE_2057','261830AD_ABC_FG_2876'];
const arrModified = arr.map(element =>
element.substr(0, element.indexOf('_')));
console.log(arrModified)
Use Array.map function so your code will look something like this
[].map(item => item.split('_')[0])
where [] is your array
in ES5 syntax it will look like
[].map(function(item) {
return item.split('_')[0];
})
Hope that helps
Just use map https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/map
with
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/split
like
var array = ["12_bla","13_ble"].map(function (el) { return el.split('_',1)[0]; });
Using a for ... of:
var arr = ['255028AD_ABC_DE_2057', '261830AD_ABC_FG_2876'];
var index = 0;
for (item of arr) {
arr[index] = item.split('_')[0];
index++;
}
console.log(arr);
You may also do like
var result = ["255028AD_ABC_DE_2057","261830AD_ABC_FG_2876"].map(s => s.replace(/_.*/,""));
console.log(result);
I have a multidimentional array:
(3) [Array(1), Array(1), Array(1)]
0:["('idDocDetail','0','$createdBy')"]
1:["('idDocDetail','2','$createdBy'),('idDocDetail','4','$createdBy')"]
2:["('idDocDetail','0','$createdBy')"]
I need to replace the string value idDocDetail with the index number, like this.
(3) [Array(1), Array(1), Array(1)]
0:["('0','0','$createdBy')"]
1:["('1','2','$createdBy'),('1','4','$createdBy')"]
2:["('2','0','$createdBy')"]
I'm trying to use replace, but I got the replace is not a function error.
array.forEach(function(item, index) {
return item.toString().replace('idDocDetail', index);
});
what am I doing wrong? Replace is the right way to do this?
I do recommend you to learn to perform changes in immutable manner. This is where Array.prototype.map plays well
const data = [
["('idDocDetail','0','$createdBy')"],
["('idDocDetail','2','$createdBy'),('idDocDetail','4','$createdBy')"],
["('idDocDetail','0','$createdBy')"]
]
const modified = data.map((item, index) =>
item.map(str => str.replace(/idDocDetail/g, index ))
)
modified.forEach(x => console.log(JSON.stringify(x)))
Here, this works for your code structure. It uses map() to produce a new array by just replacing the string of interest with the index.
EDIT: Added a nested map for clarity + regular expression to find all instances of 'idDocDetail' in the string, not just the first one. replace method when given a raw string value only handles the first instance of a string occurring.
const array = [["('idDocDetail','0','$createdBy')"],
["('idDocDetail','2','$createdBy'),('idDocDetail','4','$createdBy')"],
["('idDocDetail','0','$createdBy')"]]
var find = 'idDocDetail';
var re = new RegExp(find, 'g');
let newArray = array.map((val, i) => val.map(string => {
return string.replace(re, i)
}))
console.log(newArray)
You can loop over your array and edit it.
let array = [
["('idDocDetail','0','$createdBy')"],
["('idDocDetail','2','$createdBy'),('idDocDetail','4','$createdBy')"],
["('idDocDetail','0','$createdBy')"],
];
array.forEach((e, i) => {
array[i] = [e[0].replace(/idDocDetail/g, i)];
});
console.log(array);
You can not replace an item by calling a method on the item being replaced. Instead you need to call it on the array. You can do it this way:
for (var i=0; i<array.length; i++) {
array[i][0] = i;
}
forEach ignores the return of the callback. You need to assign to the original array at the current index.
var array = [
["('idDocDetail','0','$createdBy')"],
["('idDocDetail','2','$createdBy'),('idDocDetail','4','$createdBy')"],
["('idDocDetail','0','$createdBy')"]
];
array.forEach(function(item, index) {
array[index] = item.map(s => s.replace('idDocDetail', index));
});
console.log(array);