finding index of item in nested array - javascript

If I have an array (sub) which has its own objects each with arrays within them and I'm looking for a particular value such as id === 9, how would I find the index of the object AND the index within that object's s array?
let a = {
sub: [
{
id: 1,
s: [
{id: 5},
{id : 1}
]
},
{
id: 2,
s: [
{id: 6},
{id: 3}
]
},
{
id: 3,
s: [
{id: 9},
{id: 2}
]
}
]
}
console.log(a.sub.findIndex(a => a.s.findIndex(z => z.id === 9)))

If you're sure there's only one matching element in all your sub arrays, here's a little trick with flatMap.
let a = {
sub: [
{
id: 1,
s: [
{id: 5},
{id: 1}
]
},
{
id: 2,
s: [
{id: 6},
{id: 3}
]
},
{
id: 3,
s: [
{id: 9},
{id: 2}
]
}
]
}
console.log(a.sub.flatMap((a, i) => {
const j = a.s.findIndex(z => z.id === 9);
return j > -1 ? [i, j] : []
}));
This will return an array containing the index, i, in a.sub where a matching element is found followed by the index, j, in a.sub[i].s where the matching element was found.
Note flatMap is a relatively recent addition to the standard, so it may not work in older browsers. Be sure to use a polyfill or a transpiler like Babel, if this is a concern in your case.

Try this:
let a = {
sub: [
{
id: 1,
s: [
{id: 5},
{id : 1}
]
},
{
id: 2,
s: [
{id: 6},
{id: 3}
]
},
{
id: 3,
s: [
{id: 9},
{id: 2}
]
}
]
}
v = 9
id1 = a.sub.findIndex(e => e.s.findIndex(ee => ee.id === v)!= -1)
id2 = a.sub[id1].s.findIndex(e => e.id === v )
console.log(id1) //index of the object
console.log(id2) //index within that object's s array

Modified answer of p.s.w.g, less likely to give you an eslint error.
let a = {
sub: [
{
id: 1,
s: [
{id: 5},
{id: 1}
]
},
{
id: 2,
s: [
{id: 6},
{id: 3}
]
},
{
id: 3,
s: [
{id: 9},
{id: 2}
]
}
]
}
console.log(a.sub.flatMap((a, i) => {
const j = a.s.findIndex(z => z['id'] === 9);
return j > -1 ? [i, j] : []
}));

Related

how to guet maximum value of object with same name and Id

i have an array of objects like below
[
{value: 1, id: 1, name: "x"},
{value: 5, id: 1, name: "x"},
{value: 1, id: 1, name: "y"},
{value: 8, id: 1, name: "y"},
{value: 1, id: 2, name: "x"},
{value: 3, id: 2, name: "x"},
{value: 1, id: 2, name: "y"},
{value: 4, id: 2, name: "y"}
]
i want to guet the object with max value with the same "name" and "id"
and push it in a new array ,
the expected output is like this :
[
{value: 5, id: 1, name: "x"},
{value: 8, id: 1, name: "y"},
{value: 3, id: 2, name: "x"},
{value: 4, id: 2, name: "y"},
]
thank you
You can use reduce method to do this,
const data = [
{value: 1, id: 1, name: "x"},
{value: 5, id: 1, name: "x"},
{value: 1, id: 1, name: "y"},
{value: 8, id: 1, name: "y"},
{value: 1, id: 2, name: "x"},
{value: 3, id: 2, name: "x"},
{value: 1, id: 2, name: "y"},
{value: 4, id: 2, name: "y"}
]
const res = data.reduce((prev, curr) => {
const index = prev.findIndex((item) => item.id === curr.id && item.name === curr.name);
if(index > -1) {
const obj = prev[index];
if(obj.value < curr.value) {
prev[index] = {...obj, value: curr.value};
return prev;
}
}
prev.push(curr);
return prev;
}, []);
console.log(res);
Using Array.prototype.reduce, you can group that array using id_name key pair and store the maximum values as follows.
const input = [
{value: 1, id: 1, name: "x"},
{value: 5, id: 1, name: "x"},
{value: 1, id: 1, name: "y"},
{value: 8, id: 1, name: "y"},
{value: 1, id: 2, name: "x"},
{value: 3, id: 2, name: "x"},
{value: 1, id: 2, name: "y"},
{value: 4, id: 2, name: "y"}
];
const groupBy = input.reduce((acc, cur) => {
const key = `${cur.id}_${cur.name}`;
if (!acc[key]) {
acc[key] = cur;
}
if (acc[key].value < cur.value) {
acc[key].value = cur.value;
}
return acc;
}, {});
const output = Object.values(groupBy);
console.log(output);
Reduce is used to return a new value that is basically accumulator (adds on previous value) from all the items in the array. Here we can use it to group items using specific key. As you wrote you want to have items showing a record with biggest value having same id and name, these values can be taken as a key (lets look at them as composite private keys of this object).
On each iteration, we check if there is already an object with that key added to the list, if it wasn't we add the object we are now on (during iteration) or if it was already added if its value is smaller than the current object we are on. If the value is smaller, we override the object with the current one.
In the end, we use JS Object.values method that strips away the keys and returns only the values of the object.
const list = [
{value: 1, id: 1, name: "x"},
{value: 5, id: 1, name: "x"},
{value: 1, id: 1, name: "y"},
{value: 8, id: 1, name: "y"},
{value: 1, id: 2, name: "x"},
{value: 3, id: 2, name: "x"},
{value: 1, id: 2, name: "y"},
{value: 4, id: 2, name: "y"}
];
const groupedResults = list.reduce((result, currentObject) => {
const currentKey = currentObject.id + currentObject.name;
if (!result[currentKey] || result[currentKey].value < currentObject.value) { /* Here we check if object with certain key was assigned to previously or if it was is the value smaller than of the object that we are currently seeing */
result[currentKey] = Object.assign({}, currentObject) //We need to do copy of the object (it can be also done using object destructuring) in order to have a new object that will not be bound by reference with the original one
};
return result;
}, {});
const requestedList = Object.values(groupedResults);
console.log(requestedList)

Comparing Two Arrays with Array.filter and Pushing to New Arrays Based on Common Values

I am trying to use array.filter() to compare two arrays and separate out values that the two arrays have in common, based on a certain property (id), vs. values they don't have in common. The common ids I want to push to a new array (recordsToUpdate). And I want to push the remaining elements from arr2 to a new array (recordsToInsert).
What I've tried is not working. How can I rework this to get the results I wanted? - (which in the example here should be one array of 1 common element {id: 3}, and another array of the remaining elements from arr2):
const arr1 = [{id: 1}, {id: 2}, {id: 3}];
const arr2 = [{id: 3}, {id: 4}, {id: 5}];
let recordsToUpdate = [];
let recordsToInsert = [];
recordsToUpdate = arr1.filter(e => (arr1.id === arr2.id));
recordsToInsert = ?
console.log('recordsToUpdate: ', recordsToUpdate);
console.log('recordsToInsert: ', recordsToInsert);
The desired result should be:
recordsToUpdate = [{id: 3}];
recordsToInsert = [{id: 4}, {id: 5}];
Try this, which uses Array.prototype.find to test for whether an object exists in arr2 with a given id:
const arr1 = [{id: 1}, {id: 2}, {id: 3}];
const arr2 = [{id: 3}, {id: 4}, {id: 5}];
const recordsToUpdate = arr1.filter(e => arr2.find(obj => obj.id === e.id) !== undefined);
const recordsToInsert = arr1.filter(e => arr2.find(obj => obj.id === e.id) === undefined);
console.log('recordsToUpdate: ', recordsToUpdate);
console.log('recordsToInsert: ', recordsToInsert);
Update to Robin post using some instead of find. It is just other way around.
const arr1 = [{id: 1}, {id: 2}, {id: 3}];
const arr2 = [{id: 3}, {id: 4}, {id: 5}];
const recordsToUpdate = arr1.filter(e => arr2.some(obj => obj.id === e.id));
const recordsToInsert = arr2.filter(e => !arr1.some(obj => obj.id === e.id));
console.log('recordsToUpdate: ', recordsToUpdate);
console.log('recordsToInsert: ', recordsToInsert);
I think this is what you are after... I added values to show the replacement. If you are doing any kind of state management, be careful as I am directly mutating the current array.
const arr1 = [
{ id: 1, v: "a" },
{ id: 2, v: "b" },
{ id: 3, v: "old" }
];
const arr2 = [
{ id: 3, v: "new" },
{ id: 4, v: "e" },
{ id: 5, v: "f" }
];
function updateRecords(currentArray, updatesArray) {
const currentIds = currentArray.map(item => item.id);
updatesArray.forEach(updateItem =>
currentIds.includes(updateItem.id)
? (currentArray[
currentIds.findIndex(id => id === updateItem.id)
] = updateItem)
: currentArray.push(updateItem)
);
return currentArray;
}
console.log(updateRecords(arr1, arr2))
This now gives the option below:
[
{
"id": 1,
"v": "a"
},
{
"id": 2,
"v": "b"
},
{
"id": 3,
"v": "new"
},
{
"id": 4,
"v": "e"
},
{
"id": 5,
"v": "f"
}
]
Putting it in a function is also something you likely want to do as you will likely use this multiple places in your code.

Original array changed without any modifications done

I am trying to remove duplicate objects from an array, and keep only the objects which have the highest nb value.
Example:
From this array:
let arr = [
{id: 1, nb: 1},
{id: 1, nb: 4},
{id: 2, nb: 1},
{id: 3, nb: 1},
{id: 1, nb: 2},
{id: 1, nb: 3},
{id: 2, nb: 7},
{id: 2, nb: 8},
];
I am supposed to get this:
arr2 = [
{ id: 1, nb: 4 },
{ id: 2, nb: 8 },
{ id: 3, nb: 1 }
]
The algorithm below is very correct in theory, however I see the original array is modified by the end (see the last console.log(arr) below):
Code:
let arr = [
{id: 1, nb: 1},
{id: 1, nb: 4},
{id: 2, nb: 1},
{id: 3, nb: 1},
{id: 1, nb: 2},
{id: 1, nb: 3},
{id: 2, nb: 7},
{id: 2, nb: 8},
];
// Original array
console.log(arr);
let tmp = {};
for(let i=0; i<arr.length; i++) {
if( !tmp[arr[i].id] ) {
tmp[arr[i].id] = arr[i];
} else {
if (tmp[arr[i].id].nb < arr[i].nb ) {
tmp[arr[i].id].nb = arr[i].nb;
}
}
}
var result = Object.values(tmp);
// This output the desired result
console.log(result);
// Why the original array changed ?
console.log(arr);
This will output:
> Array [Object { id: 1, nb: 1 }, Object { id: 1, nb: 4 }, Object { id: 2, nb: 1 }, Object { id: 3, nb: 1 }, Object { id: 1, nb: 2 }, Object { id: 1, nb: 3 }, Object { id: 2, nb: 7 }, Object { id: 2, nb: 8 }]
> Array [Object { id: 1, nb: 4 }, Object { id: 2, nb: 8 }, Object { id: 3, nb: 1 }]
> Array [Object { id: 1, nb: 4 }, Object { id: 1, nb: 4 }, Object { id: 2, nb: 8 }, Object { id: 3, nb: 1 }, Object { id: 1, nb: 2 }, Object { id: 1, nb: 3 }, Object { id: 2, nb: 7 }, Object { id: 2, nb: 8 }]
Why did the original array changed when there is no processing on it apart from looping?
The original array is updated at last as the objects in your tmp map and arr share the same object reference. So changes made in tmp will be reflected in arr. You can use Object.assign() to make them point to separate reference. Try the following:
let arr = [ {id: 1, nb: 1}, {id: 1, nb: 4}, {id: 2, nb: 1}, {id: 3, nb: 1}, {id: 1, nb: 2}, {id: 1, nb: 3}, {id: 2, nb: 7}, {id: 2, nb: 8}, ];
let tmp = {};
for(let i=0; i<arr.length; i++) {
if( !tmp[arr[i].id] ) {
tmp[arr[i].id] = Object.assign({},arr[i]);
} else {
if (tmp[arr[i].id].nb < arr[i].nb ) {
tmp[arr[i].id].nb = arr[i].nb;
}
}
}
var result = Object.values(tmp);
console.log(result)
Because objects in both the arrays are sharing the same reference.
You will need to update from
tmp[arr[i].id] = arr[i];
to
tmp[arr[i].id] = JSON.parse(JSON.stringify(arr[i]));
let arr = [
{id: 1, nb: 1},
{id: 1, nb: 4},
{id: 2, nb: 1},
{id: 3, nb: 1},
{id: 1, nb: 2},
{id: 1, nb: 3},
{id: 2, nb: 7},
{id: 2, nb: 8},
];
let tmp = {};
for(let i=0; i<arr.length; i++) {
if( !tmp[arr[i].id] ) {
tmp[arr[i].id] = JSON.parse(JSON.stringify(arr[i]));
} else {
if (tmp[arr[i].id].nb < arr[i].nb ) {
tmp[arr[i].id].nb = arr[i].nb;
}
}
}
var result = Object.values(tmp);
console.log(arr); // original array unchanged

Convert array of objects to one Object using ramda.js

I have an array:
var a = [
{id: 1, val: 'a'},
{id: 2, val: 'b'},
{id: 3, val: 'c'},
{id: 4, val: 'd'},
]
And I want to get transform it to:
var b = {
1: 'a',
2: 'b',
3: 'c',
4: 'd',
}
Actually I'm using pure js:
var b = a.reduce(
(ac, pr) => ({
...ac,
[pr.id]: pr.val,
}),
{}
);
But maybe Ramda.js have something special for that purpose?
You are looking for Ramda's .mergeAll() method:
var b = R.mergeAll(a.map(function(o) {
return {
[o.id]: o.val
}
}));
The .map()call will return the custom object from each item, taking only the values, then .mergeAll() will merge the array into one object.
mergeAll Documentation:
Merges a list of objects together into one object.
Demo:
var a = [{
id: 1,
val: 'a'
},
{
id: 2,
val: 'b'
},
{
id: 3,
val: 'c'
},
{
id: 4,
val: 'd'
},
];
var b = R.mergeAll(a.map(function(o) {
return {
[o.id]: o.val
}
}));
console.log(b);
<script src="https://cdn.jsdelivr.net/ramda/0.18.0/ramda.min.js"></script>
If anyone still passes by here, it does indeed:
R.indexBy(R.prop('id'), someArray);
See indexBy in Ramda's documentation
EDIT:
Bennet is correct. If we want val as the only value per key, we can "pluck" it out after:
const createValDict = R.pipe(
R.indexBy(R.prop('id')),
R.pluck('val')
)
const valDict = createValDict(myArr)
Pluck works on objects too
Get the ordered values from each object by mapping with R.props, and use R.fromPairs to create an object:
var a = [
{id: 1, val: 'a'},
{id: 2, val: 'b'},
{id: 3, val: 'c'},
{id: 4, val: 'd'},
];
var result = R.compose(R.fromPairs, R.map(R.props(['id', 'val'])));
console.log(result(a));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
With plain Javascript, you could use a combination with Object.assign, spread syntax ..., Array#map, destructuring assignment and short hand properties.
var a = [{ id: 1, val: 'a' }, { id: 2, val: 'b' }, { id: 3, val: 'c' }, { id: 4, val: 'd' }],
result = Object.assign(...a.map(({ id, val }) => ({ [id]: val })));
console.log(result);
var a = [
{id: 1, val: 'a'},
{id: 2, val: 'b'},
{id: 3, val: 'c'},
{id: 4, val: 'd'},
]
var result = {};
for (var i=0; i<a.length; i++) {
result[a[i].id] = a[i].val;
}
console.log(result);
If you wanted something point-free, you could write:
const combine = compose(mergeAll, map(lift(objOf)(prop('id'), prop('val'))))
const {compose, mergeAll, map, lift, objOf, prop} = R;
const combine = compose(mergeAll, map(lift(objOf)(prop('id'), prop('val'))))
var a = [{id:1, val:'a'}, {id:2, val:'b'}, {id:3, val:'c'}, {id:4, val:'d'}]
console.log(combine(a));
<script src="https://cdn.jsdelivr.net/ramda/0.18.0/ramda.min.js"></script>
Here it works like a charm :
var a = [
{id: 1, val: 'a'},
{id: 2, val: 'b'},
{id: 3, val: 'c'},
{id: 4, val: 'd'},
];
// var b = R.fromPairs( a.map(Object.values) );
// Perhaps this is the more general and order independent way:
var b = R.fromPairs(a.map( ({id,val})=>[id,val] ));
console.log( b );
<script src="//cdn.jsdelivr.net/npm/ramda#latest/dist/ramda.min.js"></script>
This might be the simplest way:
pipe(map(props(['id', 'val'])), fromPairs)(a)
#spflow's answer is simpler but not guaranteed to work on all platforms. Ramda code golf is always fun!
const { fromPairs, map, pipe, props } = R
const a = [
{id: 1, val: 'a'},
{id: 2, val: 'b'},
{id: 3, val: 'c'},
{id: 4, val: 'd'},
]
const result = pipe(map(props(['id', 'val'])), fromPairs)(a)
console.log(result)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.min.js"></script>
Yet one approach:
const { indexBy, prop, pipe, pluck } = R
const a = [
{id: 1, val: 'a'},
{id: 2, val: 'b'},
{id: 3, val: 'c'},
{id: 4, val: 'd'},
]
const result = pipe(indexBy(prop('id')), pluck('val'))(a)
console.log(result)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.min.js"></script>
Simplest, point-free:
compose(fromPairs, map(values))(a)
const { compose, fromPairs, map, values } = R
const a = [
{id: 1, val: 'a'},
{id: 2, val: 'b'},
{id: 3, val: 'c'},
{id: 4, val: 'd'},
]
const result = compose(fromPairs, map(values))(a)
console.log(result)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

Is there any lodash function to achieve this?

I have an array
var a = [
{id: 1, item: 3},
{id: 1, item: 4},
{id: 1, item: 5},
{id: 2, item: 6},
{id: 2, item: 7},
{id: 3, item: 8}
]
I need output like this:
[{id: 1, items: [3, 4, 5]}, {id: 2, items: [6,7]}, {id: 3, items: [8]}]
Here's a solution that first groups by id and then maps across the groupings to get the required collection:
let result = _(a)
.groupBy('id')
.map( (group ,id) => ({id: id, items: _.map(group, 'item')}))
.value()
It's pretty ugly, but then other answers are not pretty either
var a = [
{id: 1, item: 3},
{id: 1, item: 4},
{id: 1, item: 5},
{id: 2, item: 6},
{id: 2, item: 7},
{id: 3, item: 8}
];
var ret = _.chain(a)
.groupBy(elt => elt.id)
.mapValues(elt => _.reduce(elt, (acc, sub) => acc.concat(sub.item),[]))
.map((value, key) => ({id: key, items:value}))
.value();
console.log(ret);
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>

Categories

Resources