简体   繁体   中英

How can I find and sort the indexes of the elements of an object in array in javascript

Updated Version of the Problem: my goal is to get the indexes of the of the element of this array, with the condition that the subelement param_name of key params will define the index of the object. For instance, object with key name 'caller1' should have a default index of 0, but since param_name is 'caller2' it will take index 1; similarly object 3 with key name 'caller3' will take index 0 since param_name is 'caller1'. For object 2 with key name 'caller2' since param_name is same as key name caller2 it will retain its default index of 1.

const array1 = [{
        name: 'caller1',
        cost: 12,
        params:[{param_name:'caller2',apparatus:'fittings'}]
      },
      {
        name: 'caller2',
        cost: 2,
        params:[{param_name:'caller2',apparatus:'fittings'}]
      },
      {
        name: 'caller3',
        cost: 12,
        params:[{param_name:'caller1',apparatus:'valves'}]
      }
    ];
    const results = []
    for (let j=0; j<array1.length;j++){
      results[j] = array1[j].findIndex(a => a.name==array1[j].name);
    }
    console.log(results);

You could take a Map and map the indices.

 const array = [{ name: 'caller1', cost: 12, params: [{ param_name: 'caller2', apparatus: 'fittings' }] }, { name: 'caller2', cost: 2, params: [{ param_name: 'caller2', apparatus: 'fittings' }] }, { name: 'caller3', cost: 12, params: [{ param_name: 'caller1', apparatus: 'valves' }] }], map = new Map(array.map(({ name }, i) => [name, i])), result = array.map(({ params: [{ param_name }] }) => map.get(param_name)); console.log(result);

You need to take the property from params and use that as a search parameter to use when looping over the main array

var indexes = array1.map(element => {
  var nameToCheck = element.params[0].param_name;
  for (let i = 0; i < array1.length; i++) {
    if (array1[i].name == nameToCheck) {
      return i;
    }
  }
})

Demo

 const array1 = [{ name: 'caller1', cost: 12, params: [{ param_name: 'caller2', apparatus: 'fittings' }] }, { name: 'caller2', cost: 2, params: [{ param_name: 'caller2', apparatus: 'fittings' }] }, { name: 'caller3', cost: 12, params: [{ param_name: 'caller1', apparatus: 'valves' }] } ]; var indexes = array1.map(element => { var nameToCheck = element.params[0].param_name; for (let i = 0; i < array1.length; i++) { if (array1[i].name == nameToCheck) { return i; } } }) console.log(indexes);

Note that if params actually contains more than 1 element you would need to account for that and decide which one you need to use and change the element.params[0].param_name; line accordingly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM