Filter object in javascript - javascript

I am trying to filter through an array of objects and delete one of the object but keep the rest inside an array of objects but i keep returning either an array of arrays or i create nested objects. Is it possible to send in an array of objects and return and array of objects without that specific object? Below is the code I have been trying to work with.
function deleteWorkout(workoutName) {
const updatedArray = myWorkoutToDisplay.map((item) => item.newWorkToAdd.filter((workout) => workout.name !== workoutName))
const objectArray = [{updatedArray}]
const newWorkToAdd = objectArray.filter(e => e.length)
const workouts = [{newWorkToAdd}]
setMyWorkoutToDisplay(updatedArray)
}

You can easily do this with Array.prototype.filter. I guess the easiest way to delete 1 object is like this:
//let arr = arrayLike
//let objToDelete = whatever you want to delete
let newArr = arr.filter(obj => obj !== objToDelete)
newArr now has the array, without the deleted item. arr however still has it. To delete item by index, use this:
//let arr = arrayLike
//let ind = index to delete
let newArr = arr.filter((_, index) => index !== ind)

Related

filter array of ojects with max value in javascript

Hi I have an array of objects like below:
let tbrows = [{"rowindx":0,"speciescnt":2},{"rowindx":0,"speciescnt":3},{"rowindx":1,"speciescnt":2},{"rowindx":1,"speciescnt":3}]
I want to get the maximum value of speciecnt for each row (i.e. after filtering the array) I would like it to be
let tbrows = [{"rowindx":0,"speciescnt":3},{"rowindx":1,"speciescnt":3}];
I am using the following code that I found on the web to filter an array but it only filters on one attribute of object.
const max2 = tbrows.reduce((op, item) => op = op > item.speciescnt? op : item.speciescnt, 0);
You can also using reduce() to do it
let tbrows = [{"rowindx":0,"speciescnt":2},{"rowindx":0,"speciescnt":3},{"rowindx":1,"speciescnt":2},{"rowindx":1,"speciescnt":3}]
let result = tbrows.reduce((a,c) => {
let obj = a.find(i => i.rowindx == c.rowindx)
if(!obj){
a.push(c)
}else if(c.speciescnt > obj.speciescnt){
obj.speciescnt = c.speciescnt
}
return a
},[])
console.log(result)
Turn the array into an object (right now, you're trying to turn it into just a number). Have the object be indexed by the row index, with the associated value for that row as the highest speciecnt found so far. Then you can turn the object back into an array.
const input = [{"rowindx":0,"speciescnt":2},{"rowindx":0,"speciescnt":3},{"rowindx":1,"speciescnt":2},{"rowindx":1,"speciescnt":3}];
const grouped = {};
for (const { rowindx, speciescnt } of input) {
grouped[rowindx] = Math.max(grouped[rowindx] ?? -Infinity, speciescnt);
}
const output = Object.entries(grouped)
.map(([rowindx, speciescnt]) => ({ rowindx, speciescnt }));
console.log(output);

How to filter items in the correct orderhow

Consider this array of objects and array of items i want to filter the first array to include only the objects related to the names in Array but follows the order of Array and not the order of object
object= [{name:'ali', age:10},{name:'max', age:5},{name:'john', age:6},{name:'well',age:12}]
Array= ['max','well','john']
const filterit= object.filter(item=>{
if(Array.includes(item.name)
return item.name
})
console.log(filterit)
the output result is
[{name:'max', age:5},
{name:'john', age:6},
{name:'well',age:12}]
the filter works perfect and only the objects related to names in Array gets filtered the only problem is that it gets filtered according to their order in the 'object' array and not according to the names order in 'Array' so how to fix this in order to get a filtered array in the same order as in Array cause order is very crucial to me
First of all, this filter will not work as expected, as you return the item name, it will filter the items that have falsy value for name.
const filterit= object.filter(item=>{
if(Array.includes(item.name))
return item.name
})
You shouldn't return item.name, but it should return Array.includes(item.name)
const filterit= object.filter(item => Array.includes(item.name))
And to make the array with the same sorting.
let array = [{name:'ali', age:10},{name:'max', age:5},{name:'john', age:6},{name:'well',age:12}]
let sortedArray = []
let namesArray = ['max','well','john']
namesArray.forEach(name => {
let item = array.find(i => i.name === name)
if (item) sortedArray.push(item)
})
console.log(sortedArray)
Just iterate over the Array itself and filter that obj's array on match
consdt objArr = object= [{name:'ali', age:10},{name:'max', age:5},{name:'john', age:6},{name:'well',age:12}]
const myArr = ['max','well','john']
const result = myArr.filter(elem => {
return objArr.find(item => item.name == elem)
})

Find Unique value from an array based on the array's string value (Javascript)

so I want to find unique values from an array.
so for example I have this array:
const mainArr = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884']
so I want to find the first matching value for each unique item.
for example, in the array, I have two strings with the shape prefix, six items with the size prefix, and two items with the height prefix.
so I want to output to be something like
const requiredVal = ["shape-10983", "size-2364", "height-3399"]
I want only the first value from any set of different values.
the simplest solution will be to iterate on the list and storing what you got in a dictionary
function removeSimilars(input) {
let values = {};
for (let value of input) {//iterate on the array
let key = value.splitOnLast('-')[0];//get the prefix
if (!(key in values))//if we haven't encounter the prefix yet
values[key] = value;//store that the first encounter with the prefix is with 'value'
}
return Object.values(values);//return all the values of the map 'values'
}
a shorter version will be this:
function removeSimilars(input) {
let values = {};
for (let value of input)
values[value.splitOnLast('-')[0]] ??= value;
return Object.values(values);
}
You could split the string and get the type and use it aks key for an object along with the original string as value. At result take only the values from the object.
const
data = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884'],
result = Object.values(data.reduce((r, s) => {
const [type] = s.split('-', 1);
r[type] ??= s;
return r;
}, {}));
console.log(result);
If, as you mentioned in the comments, you have the list of prefixes already available, then all you have to do is iterate over those, to find each first element that starts with that prefix in your full list of possible values:
const prefixes = ['shape', 'size', 'height'];
const list = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884']
function reduceTheOptions(list = [], prefixes = [], uniques = []) {
prefixes.forEach(prefix =>
uniques.push(
list.find(e => e.startsWith(prefix))
)
);
return uniques;
}
console.log(reduceTheOptions(list, prefixes));
Try this:
function getRandomSet(arr, ...prefix)
{
// the final values are load into the array result variable
result = [];
const randomItem = (array) => array[Math.floor(Math.random() * array.length)];
prefix.forEach((pre) => {
result.push(randomItem(arr.filter((par) => String(par).startsWith(pre))));
});
return result;
}
const mainArr = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884'];
console.log("Random values: ", getRandomSet(mainArr, "shape", "size", "height"));
I modified the #ofek 's answer a bit. cuz for some reason the ??= is not working in react project.
function removeSimilars(input) {
let values = {};
for (let value of input)
if (!values[value.split("-")[0]]) {
values[value.split("-")[0]] = value;
}
return Object.values(values);
}
create a new array and loop over the first array and check the existing of element before in each iteration if not push it to the new array

Filter objects from array

I have an object TS_List with a key thread_ts
and an array tsColValsArray
I want to remove items where tsColValsArray[i] is part of TS_List.thread_ts
This works for the third item in the array
var TS_List1 = TS_List.filter(item => !item.thread_ts.includes(tsColValsArray[2]));
but how do I filter for all the array
I thought it would be something like
var TS_List1 = TS_List.filter(item => !item.thread_ts.includes(tsColValsArray));
You can combile Array#some with Array#filter
var TS_List1 = TS_List.filter(item => !tsColValsArray.some(e => item.thread_ts.includes(e)));

Convert string array into object with same key/value

How do I convert ["one","two","three"] into {one:"one", two:"two", three:"three"}
import stringArray from './a.js';
class b {
hashmap = stringArray// convert this into Object here inline.
}
Before you jump I know of for how to achieve this in say constructor() with tricks like forEach, for in loop etc. Is there a simple one line code to achieve this in the class property not inside a function.
Lodash
You can use _.zipObject. It accepts two arrays - one for keys, another for values but if you just use the same array twice you'd get matching pairs:
const arr = ["one","two","three"];
const obj = _.zipObject(arr, arr);
console.log(obj);
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.15/lodash.min.js"></script>
Plain JavaScript
You can use Object.fromEntries to do the same thing. It works with an array of key-value pairs, so you'll have to transform yours to that:
const arr = ["one","two","three"];
const matchingKeyValuePairs = arr.map(x => [x, x]);
const obj = Object.fromEntries(matchingKeyValuePairs);
console.log(obj);
Also you can use Array#reduce to generate an object with a computed property name:
const arr = ["one","two","three"];
const obj = arr.reduce((acc, item) => ({...acc, [item]: item}), {});
console.log(obj);
data = ["one","two","three"];
data = data.map(e => [e,e]) // keyvalue pairs [["one","one"],["two","two"],["three","three"]]
data = Object.fromEntries(data); // {"one":"one","two":"two","three":"three"}
map will convert each element of your input array to a structure you want.
In this case, we want to convert each element to an array with the element repeated twice in it
Object.froEntries will convert a list of key-value pair to an Object
This can be also done with the plain old for loop
data = ["one","two","three"];
obj = {};
for(let i = 0; i < data.length ; i++){
obj[data[i]] = data[i];
}
Try this:
const arr = ["one","two","three"]
let obj = {}
arr.forEach(item => {obj[item] = item})
document.write(JSON.stringify(obj))
Lodash has the _.keyBy() function, that creates an object from an array by generating keys from the values via the function supplied (the iteratee). The default iteratee is _.identity(), which returns the value.
const arr = ["one","two","three"];
const obj = _.keyBy(arr);
console.log(obj);
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.15/lodash.min.js"></script>

Categories