JS create new array from certain item - javascript

I have 2 dimensional array myArray:
[
[ '567576', 'John', 'Doe' ],
[ '098897', 'John', 'Doe' ],
[ '543539', 'John', 'Doe' ],
[ '234235', 'John', 'Doe' ],
[ '345348', 'John', 'Doe' ],
[ '432574', 'John', 'Doe' ]
]
Is it possible to create a new array from myArray starting from a certain first value?
For example create a new array starting from id 543539. Anything above the array containing 543539 will not be added.

You can make use of findIndex() which returns the index of the first item that matches the condition.
Combine it with slice() to cut your array at the specific position:
const myArray = [
['567576', 'John', 'Doe'],
['098897', 'John', 'Doe'],
['543539', 'John', 'Doe'],
['234235', 'John', 'Doe'],
['345348', 'John', 'Doe'],
['432574', 'John', 'Doe']
]
console.log(myArray.slice(myArray.findIndex(item => item[0] === "543539")));

Sure, assuming all the internal arrays are structured the same way, you can do something like let newArray = myArray.filter(innerArray => Number(innerArray[0]) > 543539)
Edit: This is assuming you want all subarrays where the first item is a number larger than 54539, as opposed to finding all of the subarrays that physically follow the first occurrence of a subarray with 54539 as the first value

Yes, that is possible and straightforward process.
You can use the javascript map method which returns a new array
newArray = myArray.map(item=> item[0])

Related

Take elements by key in objects array

Let's say I have got an array of objects like this:
const a = [
0: {name: 'John', lastName: 'Smith'}
1: {name: 'Juan', lastName: 'Perez'}
myKey: true
myKey2: false
]
How can I extract from my array just the value of 'myKey'?
So the expected output would be
const myKeyValue = true
If you want a single value and you know the key, use:
const myKeyValue = a.myKey

Accessing duplicates in objects in the same array?

I have an array with multiple objects
arr = [
{name: 'xyz',
age: 13,
},
{name: 'abc',
age: 15,
},
{name: 'abc',
age: 15,
}]
how do I find the duplicate in this array and remove the object that is duplicated in the array? They are all in one array.
Apologies. I just realized what I am trying to do is, remove the object entirely if there's a duplicate in one key... so if the age is similar, I will remove object name "def". Is this possible?
arr = [
{name: 'xyz',
entry: 1,
age: 13,
},
{name: 'abc',
entry: 2,
age: 15,
},
{name: 'def',
age: 13,
entry: 3
}]
You could achieve this by the following steps:
transform each element into an object that is key-sorted, this will make objects consistent in terms of key-value pairs order, which will help us in the next step
map the array into JSON-stringified value, and store it into a Set(), which would help us store only unique stringified objects
turn the Set() back into array
map the array back into objects by JSON.parse() each element
const arr = [
{ name: "xyz", age: 13 },
{ age: 15, name: "abc" },
{ name: "abc", age: 15 },
]
const sortKeys = obj =>
Object.fromEntries(
Object.entries(obj).sort((keyValuePairA, keyValuePairB) =>
keyValuePairA[0].localeCompare(keyValuePairB[0])
)
)
const res = Array.from(
arr
.map(sortKeys)
.map(el => JSON.stringify(el))
.reduce((set, el) => set.add(el), new Set())
).map(el => JSON.parse(el))
console.log(res)
References
Set
Object.entries()
Object.fromEntries()

Assign Keys when converting array to json - Node JS [duplicate]

This question already has answers here:
Javascript - convert array of arrays into array of objects with prefilled values
(4 answers)
Closed 2 years ago.
I Have some array like below:
[
[
'James',
23,
'male'
],
[
'Britney',
45,
'female'
]
]
I would like to turn that into a json looking like:
[
{
'name': 'James',
'age': 23,
'gender'': 'male'
},
{
'name': 'Britney',
'age': 45,
'gender'': 'female'
}
]
I understand the json stringify part to convert the array to json but not sure how to create the keys for the values in an efficient way. Any help is greatly appreciated.
Use map, then destruct the array and return an object.
const arr = [
[
'James',
23,
'male'
],
[
'Britney',
45,
'female'
]
]
const res = arr.map(([name, age, gender]) => ({
name,
age,
gender
}))
console.log(res);
You can do this with map with proper destructuring(for shortcut):
var a=[ [ 'James', 23, 'male' ], [ 'Britney',45,'female']];
var result = a.map(([name,age,gender])=>({name, age, gender}));
console.log(result);

How to remove duplicates from an array using forEach method in javascript

I have an array in that I have objects and strings now my goal is to filter all duplicates from strings and objects.
If you don't understand, please put a comment
const data = [
'apple',
'mango',
'orange',
'grapes',
'apple',
'mango',
{
name: 'Mark',
age: 28
},
{
name: 'Mark',
age: 28
},
{
name: 'James',
age: 28
},
'sapota',
'gaua',
{
name: 'Williams',
age: 26
},
{
name: 'John',
age: 24
},
'gaua'
]
console.log(data)
One method you could use assuming you have no circular data structures
function removeDup(arr){
let known = [];
return arr.filter(elem => {
let str = JSON.stringify(elem); // Get string of whatever item we are dealing with
if(!known.includes(str)){ //Check to see if we have seen this item before
known.push(str); //If we havnt add it to seen list
return true;
}
return false;
});
}
Obviously this is constrained to anything that JSON.stringify can handle.
Also, this method assumes that in an array like:
[{name: 'name'}, 'name']
the two names are different things and will both get returned. If you want to treat them the as duplicates let me know
Note this doesn't use a forEach loop but could VERY easily be change to use one.

Lodash. How to get array values from object if you know array keys?

For example, you have an object.
{ id: 1, firstName: 'John', lastName: 'Doe' }
How to get an array from the object if you know array keys? You have array keys
['firstName', 'lastName']
and you should get array
['John', 'Doe']
I use Lodash.
You can you _.at():
const obj = { id: 1, firstName: 'John', lastName: 'Doe' };
const keys = ['firstName', 'lastName'];
const result = _.at(obj, keys);
console.log('RESULT:', result);
<script src='https://cdn.jsdelivr.net/lodash/4.16.6/lodash.min.js'></script>
You don't need lodash.
Just use Array.prototype.map to get values from key array.
const obj = { id: 1, firstName: 'John', lastName: 'Doe' };
const filterKey = ['firstName', 'lastName'];
console.log('FILTERED:', filterKey.map(key => obj[key]));
const keys = Object.keys({ id: 1, firstName: 'John', lastName: 'Doe' });
const values = Object.values({ id: 1, firstName: 'John', lastName: 'Doe' });
console.log(keys)
console.log(values)
You don't need to use Lodash, using plain javascript will do it.
Use Object.keys() for getting all the keys of an object and Object.values() to get an array with all the values that an object has.

Categories